Я пытаюсь извлечь журнал из базы данных mysql, используя API-интерфейс Springboot REST, но журналы поступают в несколько повторений, а не в одну строку. У меня есть только одна строка в моей базе данных, но когда она вызывается с помощью GET, она поступает как повторяющиеся журналы. Проверьте изображение, чтобы увидеть его:
Ниже приведен код для классов сущностей, которые создали эти журналы. Первый - это 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="log")
public class UserLog {
//define field
@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;
//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<Action> getAction() {
return action;
}
public void setAction(List<Action> action) {
this.action = action;
}
@Override
public String toString() {
return "Log [userId=" + userId + ", sessionId=" + sessionId + "]";
}
}
Вот другой класс сущности 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="action")
public class Action {
//declare & annotate your fields
@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;
}
//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 "Action [time=" + time + ", type=" + type + ", userLog=" + userLog + "]";
}
}
Вот класс реализации dao
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<UserLog> findAll() {
//get the current hibernate session from entity manager
Session currentSession = entityManager.unwrap(Session.class);
//create a query
Query <UserLog> theQuery =
currentSession.createQuery("from UserLog", UserLog.class);
//execute query and get result list
List<UserLog> 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("delete from log where id=:theuserId");
theQuery.setParameter("theuserId", theId);
theQuery.executeUpdate();
}
}
и контроллер остальных
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("/api")
public class UserLogRestController {
@Autowired
private UserLogDAO userLogDao;
//inject logDao using constructor injection
public UserLogRestController(UserLogDAO theUserLogDao) {
}
//expose logs and return list of logs
@GetMapping("/userLog")
public List<UserLog> findAll(){
return userLogDao.findAll();
}
}
пожалуйста, помогите мне разобраться в этом. Заранее спасибо