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

Iredafe Owolabi :

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:

enter image description here

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="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 + "]";
    }

}

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="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 + "]";
    }


}

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<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();

    }

} 

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("/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();

    }

}

please help me figure this out. Thanks in advance

kokuone :

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="log_id")
 private UserLog userLog;


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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=284727&siteId=1