I have three Entities i'm modeling and am having issues with the associated annotations. I basically have a class that I intend on returning to the caller, a nested listed of Project's and the Project can contain a nested list of Endpoint's. It's a top-level has-a one-to-many, then the nested one-to-many has two one-to-many's.
I've played with @JoinColumn
annotations, i've attempted to put a @ManyToOne
on the other side of the OneToMany's (but it doesn't like that it's a Long..). I'm just fairly new and unsure on how to do this. I think the mappedById
is the solution, but i'm uncertain.
Main Issue: This code allows me to "save" to the database, but upon retrieval, the list of Project's inside the DownDetectorPackage is empty.
A CascadeType.ALL throws referential integrity errors that I don't completely understand.
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Builder
public class DownDetectorPackage {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@OneToMany(mappedBy="id",fetch = FetchType.EAGER)
private List<Project> projects;
@Temporal(TemporalType.DATE)
private Date dateJobsLastRan;
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Project{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String projectName;
@OneToMany(mappedBy="id")
private List<Service> externalDependencies;
@OneToMany(mappedBy="id")
private List<Service> endpoints;
}
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Service {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String url;
private Boolean endpointIsUp;
private String serviceName;
}
You should be using @JoinColumn instead of mappedBy. MappedBy can be used when you have used @ManyToOne in the other class too, which you haven't.
So your final class should look something like this (this is applicable for the other classes too which you have mentioned) :
public class DownDetectorPackage {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@JoinColumn(name = "downDetectorPackageId")
@OneToMany(fetch = FetchType.EAGER)
private List<Project> projects;
@Temporal(TemporalType.DATE)
private Date dateJobsLastRan;
Also, remember to state the parent object name in @JoinColumn annotation, since it would create a column for that foreign key.