从mysql数据库中使用springboot和hibernate检索的日志数据存在问题。

huangapple go评论151阅读模式
英文:

Issue with the log data retrieved from mysql db using springboot and hibernate

问题

以下是翻译好的部分:

UserLog.java:

package com.dafe.spring.applogger.entity;

import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name="log")
public class UserLog {

    //定义字段

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id")
    private int id;

    @Column(name="user_id")
    private String userId;

    @Column(name="session_id")
    private String sessionId;

    @OneToMany(mappedBy="userLog",cascade=CascadeType.ALL)
    private List<Action> action;

    //定义构造函数

    public UserLog() {
    	
    }
    
    public UserLog(String userId, String sessionId) {
        this.userId = userId;
        this.sessionId = sessionId;
    }

    //定义getter和setter方法

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getSessionId() {
        return sessionId;
    }

    public void setSessionId(String sessionId) {
        this.sessionId = sessionId;
    }

    public List<Action> getAction() {
        return action;
    }

    public void setAction(List<Action> action) {
        this.action = action;
    }

    @Override
    public String toString() {
        return "Log [userId=" + userId + ", sessionId=" + sessionId + "]";
    }
}

Action.java:

package com.dafe.spring.applogger.entity;

import java.sql.Timestamp;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name="action")
public class Action {

    //声明和注释字段
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id")
    private int id;

    @Column(name="time")
    private Timestamp time;

    @Column(name="type")
    private String type;

    @ManyToOne
    @JoinColumn(name="log_id")
    private UserLog userLog;

    public Action(int id, Timestamp time, String type, UserLog userLog) {
        this.id = id;
        this.time = time;
        this.type = type;
        this.userLog = userLog;
    }

    //创建和生成构造函数
    public Action() {

    }

    public Action(Timestamp time, String type, UserLog userLog) {
        this.time = time;
        this.type = type;
        this.userLog = userLog;
    }

    //生成getter和setter方法
    public Timestamp getTime() {
        return time;
    }

    public void setTime(Timestamp time) {
        this.time = time;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public UserLog getUserLog() {
        return userLog;
    }

    public void setUserLog(UserLog userLog) {
        this.userLog = userLog;
    }

    //生成toString方法
    @Override
    public String toString() {
        return "Action [time=" + time + ", type=" + type + ", userLog=" + userLog + "]";
    }
}

UserLogDaoHibernateImplementation.java:

package com.dafe.spring.applogger.dao;

import java.util.List;

import javax.persistence.EntityManager;

import org.hibernate.Session;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.dafe.spring.applogger.entity.UserLog;

@Repository
public class UserLogDaoHibernateImplementation implements UserLogDAO {

    //定义EntityManager字段
    private EntityManager entityManager;

    //通过构造函数注入
    @Autowired
    public UserLogDaoHibernateImplementation(EntityManager theEntityManager) {
        entityManager = theEntityManager;
    }

    @Override
    public List<UserLog> findAll() {
        //从EntityManager获取当前Hibernate会话
        Session currentSession = entityManager.unwrap(Session.class);

        //创建查询
        Query<UserLog> theQuery = currentSession.createQuery("from UserLog", UserLog.class);

        //执行查询并获取结果列表
        List<UserLog> userLog = theQuery.getResultList();

        //返回结果
        return userLog;
    }

    @Override
    public UserLog findById(int theId) {
        //获取当前会话
        Session currentSession = entityManager.unwrap(Session.class);

        //获取UserLog
        UserLog userLog = currentSession.get(UserLog.class, theId);

        //返回UserLog
        return null;
    }

    @Override
    public void save(UserLog theUserLog) {
        //获取当前会话
        Session currentSession = entityManager.unwrap(Session.class);

        //保存或更新
        currentSession.saveOrUpdate(theUserLog);
    }

    @Override
    public void deleteById(int theId) {
        //获取当前Hibernate会话
        Session currentSession = entityManager.unwrap(Session.class);

        //使用主键删除对象
        Query theQuery = currentSession.createQuery("delete from log where id=:theuserId");
        theQuery.setParameter("theuserId", theId);
        theQuery.executeUpdate();
    }
}

UserLogRestController.java:

package com.dafe.spring.applogger.rest;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.dafe.spring.applogger.dao.UserLogDAO;
import com.dafe.spring.applogger.entity.UserLog;

@RestController
@RequestMapping("/api")
public class UserLogRestController {

    @Autowired
    private UserLogDAO userLogDao;

    //使用构造函数注入userLogDao
    public UserLogRestController(UserLogDAO theUserLogDao) {

    }

    //公开logs并返回logs列表
    @GetMapping("/userLog")
    public List<UserLog> findAll() {
        return userLogDao.findAll();
    }
}
英文:

I am trying to retrieve a log from mysql database using a Springboot REST api but the logs are coming in multiple repetitions instead of just one line. I only have data in one row in my database but when it gets called using the GET, it comes in as repetitive logs. Check the picture to see it:

从mysql数据库中使用springboot和hibernate检索的日志数据存在问题。

Below is the code for the entity classes that produced these logs. First one is UserLog:

package com.dafe.spring.applogger.entity;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name=&quot;log&quot;)
public class UserLog {
//define field
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name=&quot;id&quot;)
private int id;
@Column(name=&quot;user_id&quot;)
private String userId;
@Column(name=&quot;session_id&quot;)
private String sessionId;
@OneToMany(mappedBy=&quot;userLog&quot;,cascade=CascadeType.ALL)
private List&lt;Action&gt;action;
//define constructors
public UserLog() {
}
public UserLog(String userId, String sessionId) {
this.userId = userId;
this.sessionId = sessionId;
}
//define getters and setters
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getSessionId() {
return sessionId;
}
public void setSessionId(String sessionId) {
this.sessionId = sessionId;
}
public List&lt;Action&gt; getAction() {
return action;
}
public void setAction(List&lt;Action&gt; action) {
this.action = action;
}
@Override
public String toString() {
return &quot;Log [userId=&quot; + userId + &quot;, sessionId=&quot; + sessionId + &quot;]&quot;;
}
}

Here is the other entity class Action:

package com.dafe.spring.applogger.entity;
import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name=&quot;action&quot;)
public class Action {
//declare &amp; annotate your fields
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name=&quot;id&quot;)
private int id;
@Column(name=&quot;time&quot;)
private Timestamp time;
@Column(name=&quot;type&quot;)
private String type;
@ManyToOne
@JoinColumn(name=&quot;log_id&quot;)
private UserLog userLog;
public Action(int id, Timestamp time, String type, UserLog userLog) {
this.id = id;
this.time = time;
this.type = type;
this.userLog = userLog;
}
//create and generate constructor
public Action() {
}
public Action(Timestamp time, String type, UserLog userLog) {
this.time = time;
this.type = type;
this.userLog = userLog;
}
//generate getters and setters
public Timestamp getTime() {
return time;
}
public void setTime(Timestamp time) {
this.time = time;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public UserLog getUserLog() {
return userLog;
}
public void setUserLog(UserLog userLog) {
this.userLog = userLog;
}
//generate toString 
@Override
public String toString() {
return &quot;Action [time=&quot; + time + &quot;, type=&quot; + type + &quot;, userLog=&quot; + userLog + &quot;]&quot;;
}
}

here is the dao implementation class

package com.dafe.spring.applogger.dao;
import java.util.List;
import javax.persistence.EntityManager;
import org.hibernate.Session;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.dafe.spring.applogger.entity.UserLog;
@Repository
public class UserLogDaoHibernateImplementation implements UserLogDAO {
//define field for entity manager
private EntityManager entityManager;
//set up constructor injection
@Autowired
public UserLogDaoHibernateImplementation(EntityManager theEntityManager) {
entityManager= theEntityManager;
}
@Override
public List&lt;UserLog&gt; findAll() {
//get the current hibernate session from entity manager
Session currentSession = entityManager.unwrap(Session.class);
//create a query
Query &lt;UserLog&gt; theQuery = 
currentSession.createQuery(&quot;from UserLog&quot;, UserLog.class);
//execute query and get result list
List&lt;UserLog&gt; userLog = theQuery.getResultList();
//return the results
return userLog;
}
@Override
public UserLog findById(int theId) {
//get the current session
Session currentSession = entityManager.unwrap(Session.class);
//get the userLog
UserLog userLog = 
currentSession.get(UserLog.class, theId);
//return the userLog
return null;
}
@Override
public void save(UserLog theUserLog) {
//get the current session
Session currentSession = entityManager.unwrap(Session.class);
//save
currentSession.saveOrUpdate(theUserLog);
}
@Override
public void deleteById(int theId) {
//get the current hibernate session
Session currentSession = entityManager.unwrap(Session.class);
//delete object with primary key
Query theQuery = 
currentSession.createQuery(&quot;delete from log where id=:theuserId&quot;);
theQuery.setParameter(&quot;theuserId&quot;, theId);
theQuery.executeUpdate();
}
} 

and the rest controller


package com.dafe.spring.applogger.rest;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.dafe.spring.applogger.dao.UserLogDAO;
import com.dafe.spring.applogger.entity.UserLog;
// this api selects all the 
@RestController
@RequestMapping(&quot;/api&quot;)
public class UserLogRestController {
@Autowired
private UserLogDAO userLogDao;
//inject logDao using constructor injection
public UserLogRestController(UserLogDAO theUserLogDao) {
}
//expose logs and return list of logs
@GetMapping(&quot;/userLog&quot;)
public List&lt;UserLog&gt; findAll(){
return userLogDao.findAll();
}
}

please help me figure this out. Thanks in advance

答案1

得分: 0

我最近遇到了这个问题,我已经通过在关联的地方添加这个注释 @JsonIgnore 来进行了修复,你也可以尝试看看是否对你有效。

 @JsonIgnore
@ManyToOne
@JoinColumn(name="log_id")
private UserLog userLog;
@JsonIgnore
@OneToMany(mappedBy="userLog",cascade=CascadeType.ALL)
private List<Action> action;
英文:

I had this issue recently and I have fixed putting this anottation @JsonIgnore
at relationships, you can try if it works for you too

 @JsonIgnore
@ManyToOne
@JoinColumn(name=&quot;log_id&quot;)
private UserLog userLog;
@JsonIgnore
@OneToMany(mappedBy=&quot;userLog&quot;,cascade=CascadeType.ALL)
private List&lt;Action&gt;action;

huangapple
  • 本文由 发表于 2020年3月15日 06:13:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/60687780.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定