I have an application in which I am trying to implement the ManyToMany relationship between two objects using Hibernate as my JPA provider.
The example I'm trying to do is unidirectional, in which a camera can have multiple lenses and lenses that can be inserted into multiple cameras.
Below is my entity class ... (just pasting the appropriate part)
Camera:
@Entity @Table(name = "CAMERAS") public class Camera implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "CAM_ID", nullable = false) private Long camId; @Column(name="CAMERA_BRAND") private String cameraBrand; @ManyToMany(cascade={CascadeType.PERSIST, CascadeType.MERGE},fetch=FetchType.EAGER) @JoinTable(name="CAMERA_LENS", joinColumns=@JoinColumn (name="CAM_ID"), inverseJoinColumns=@JoinColumn (name="LENS_ID")) private Set<Lens> lenses = new HashSet<Lens>(); ... }
Lens:
@Entity @Table(name = "LENSES") public class Lens implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "LENS_ID", nullable = false) private Long lensId; @Column(name="LENS_NAME") private String name; ... }
In a test case, I'm trying to save a camera instance in a way like this ...
@Test public void test_saveCameraLenseManyToMany() { Camera cam = new Camera(); cam.setCameraBrand("Nikon"); Set<Camera> cameras = new HashSet<Camera>(); cameras.add(cam); Set<Lens> lenses = new HashSet<Lens>(); Lens lens1 = new Lens(); lens1.setName("WideAngle"); lenses.add(lens1); cam.setLenses(lenses);
Persistence is successful and there is no error / exception caused by Hibernate. However, contrary to expectations, the line is not created in JoinTable (CAMERA_LENS in this case). A line is created only in each of the lens and camera tables, thereby not serving the purpose of ManyToMany. However, a DDL is created for the connection table, and it is also created, but it just has no records.
Any help or pointers would be greatly appreciated.
java orm jpa many-to-many
Pays
source share