I have an application in which I am trying to implement ManyToMany relation between 2 entities using Hibernate as my JPA provider.
The example I am trying is an uni-directional one, wherein a Camera can have multiple Lenses and Lense can fit into multiple Cameras.
Following is my entity class...(Just pasting the relevant part of it)
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 the test-case, I try to persist the Camera instance 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);
// concreteDAO.saveLens(lens1);
concreteDAO.saveCamera(cam);
}
The persistence happens successfully, and there is no error/exception thrown by Hibernate. However, contrary to expectation, a row is not created in the JoinTable (CAMERA_LENS in this case). A row is created in each of Lens and Camera tables only, thereby not serving the purpose of ManyToMany. However, the DDL is generated for the join table and it is created as well, but just that it does not have any records.
Any assistance or pointers would be much appreciated.