My entities are: the ID of device which is deiveID has many-to-many relationship with the ID of Lib which is rID
my test code is : two new device entities want to set the same new libentity
the problem is : if i use the same entitymanager to persist that 2 new device entities, it will be ok. but if i use 2 different entitymanager instance to persist them ,the error"primary key violation" will come out. I think the entitymanger try to persist the libentity at the second time, which has already been persisted in the first time.
--------------deviceinfo entity ------------------------------------------------
@Entity
@Table(name="deviceInfo")
public class DeviceInfoEntity extends BaseEntity implements Serializable{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long deviceId;
....
@ManyToMany(cascade=CascadeType.ALL,fetch=FetchType.LAZY)
@JoinTable(name = "device_lib", joinColumns = @JoinColumn(name = "deviceInfo_id",
referencedColumnName="deviceId"),
inverseJoinColumns = @JoinColumn(name = "lib_id", referencedColumnName="rId"))
private List<LibEntity> resourceList = null;
......
}
-------------------------lib entity ---------------------------------------------
@Entity
@Table(name="lib")
public class LibEntity extends BaseEntity implements Serializable{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long rId;
@ManyToMany(mappedBy = "resourceList", cascade=CascadeType.ALL,
fetch=FetchType.LAZY, targetEntity=DeviceInfoEntity.class)
private List<DeviceInfoEntity> deviceInfolist = null;
.....
}
my test code is:
EntityManagerFactory emFactory = Persistence.createEntityManagerFactory("testPU");
EntityManager em = emFactory.createEntityManager();
LibEntity libEntity = new LibEntity();
DeviceInfoEntity dEntity = new DeviceInfoEntity();
dEntity.setName("dadadada");
dEntity.setLibEntity(libEntity);
DeviceInfoEntity dEntity2 = new DeviceInfoEntity();
dEntity2.setName("dadadadadddddd");
dEntity2.setLibEntity(libEntity);
em.getTransaction().begin();
em.persist(dEntity);
em.getTransaction().commit();
em.close();
EntityManager em2 = emFactory.createEntityManager();
em2.getTransaction().begin();
em2.persist(dEntity2);
em2.getTransaction().commit();
the error is :
Unique index or primary key violation: "PRIMARY KEY ON PUBLIC.LIB(RID)"; SQL statement:
INSERT INTO lib (RID) VALUES (?) [23505-165]
Thanks