Reputation: 929
I'm new to JPA and was wondering if JPA contains a solution for my problem. Els I will just need to create a ManyToMany relationship.
My application contains roads and camera's. A road starts and ends with a camera. I created this by creating a property cameraPointA
and cameraPointB
in the RoadSegment
class. This created a many to two relationship. I thought I could define this as two many to one relationships but this seems not possible.
CameraPoint.java
@Entity
public class CameraPoint implements Serializable {
@Id @GeneratedValue
private long id;
@OneToMany (mappedBy = "cameraPointA or cameraPointA") //<== The Problem
private List<RoadSegment> roads;
//...
}
RoadSegment.java
@Entity
public class RoadSegment implements Serializable {
@Id @GeneratedValue
private long id;
@ManyToOne(cascade = CascadeType.ALL)
private Region region;
@ManyToOne(optional=false)
private CameraPoint cameraPointA;
@ManyToOne(optional=false)
private CameraPoint cameraPointB;
//...
}
Upvotes: 0
Views: 162
Reputation: 1646
I don't know if this will work but maybe you can try adding to CameraPoint
another list of RoadSegments
, which indicate the Camera has a list of roads where the camera is the start and the other list indicates the camera is the last.
@Entity
public class CameraPoint implements Serializable {
@Id @GeneratedValue
private long id;
@OneToMany (mappedBy = "cameraPointA")
private List<RoadSegment> roadsA;
@OneToMany (mappedBy = "cameraPointB")
private List<RoadSegment> roadsB;
//...
}
Is really necessary to use bidirectional relationship ? Maybe it is not and your model would be more easy.
For example, if you always reach to the CameraPoint
from a RoadSegment
then you don't need the @OneToMany
relationship on CameraPoint
.
The same applies for the inverse mode, if you always get a RoadSegment
from a previous CameraPoint
, then the @ManyToOne
relationship is not necessary.
Upvotes: 1