0

I am using Spring Boot and Hibernate to save two objects in MYSQL database. "Health" has a OneToMany relationship with "Checks".

HealthRepository.java:

import org.springframework.data.repository.CrudRepository;
import healthcheckapi.model.Health;

public interface HealthRepository extends CrudRepository<Health, Integer> {

}

Health Entity:

@Entity
@Table(name="health")
public class Health {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String server;
    private String description;
    private String timestamp;
    private String offset;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "health", fetch = FetchType.LAZY)
    private List<Checks> checks;

    public Health() {

    }

    public Health(int id, String server, String description, String timestamp, String offset, List<Checks> checks) {

        this.server = server;
        this.description = description;
        this.timestamp = timestamp;
        this.offset = offset;
        this.checks = checks;
    }
//getters&setters

Checks Entity:

@Entity
@Table(name="checks")
public class Checks {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String name;
    private int status;

    @ManyToOne(/*cascade = CascadeType.MERGE,*/ targetEntity = Health.class, fetch = FetchType.EAGER)
    @JoinColumn(name = "healthid", referencedColumnName="id")
    private Health health;

    public Checks() {

    }

    public Checks(String name, int status) {

        this.name = name;
        this.status = status;
    }
//getters&setters

JSON data being passed in:

{  
    "server": "Server244",
    "description": "Fine",
    "timestamp": "00:02:30",
    "offset": "00:01:00",
    "checks": [
        {  
            "name": "cpu",
            "status": 90
        },
        {

            "name": "service",
            "status": 88
        },
        {

            "name": "other",
            "status": 76
        }
    ]
}

Problem:

The list of check objects are successfully persisted in their database, as are the health objects.

However, when retrieving health objects, only an empty check object array is returned, despite the database having the foreign key relationship.

There is virtually no logic in any other class, this is defined in the annotations of the entity classes.

MRDJR97
  • 656
  • 2
  • 8
  • 22
  • You have lazy loading of checks in health. For more info about lazy loading https://stackoverflow.com/questions/2192242/what-is-lazy-loading-in-hibernate – Unknown Mar 30 '18 at 13:42
  • is the `mappedBy = "health"` correct? It is specified by the inverse end of the relationship - ie. not the owner – msp Mar 30 '18 at 14:07

0 Answers0