我的实体是:设备的 ID 是 deiveID 与 Lib 的 ID 是 rID 有多对多的关系
我的测试代码是:两个新设备实体想要设置相同的新自由度
问题是:如果我使用同一个实体管理器来持久化这 2 个新设备实体,那就没问题了。但是如果我使用 2 个不同的 entitymanager 实例来持久化它们,则会出现错误“主键违规”。我认为实体经理第二次尝试坚持自由,第一次已经坚持了。
--------------设备信息实体 ---------------------------------- --------------
@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
@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;
.....
}
我的测试代码是:
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();
它会出现错误:
Unique index or primary key violation: "PRIMARY KEY ON PUBLIC.LIB(RID)"; SQL statement:
INSERT INTO lib (RID) VALUES (?) [23505-165]
但如果我使用相同的 EntityManager,则不会发生错误。有没有人知道是什么原因?这是由cascade=CascadeType.ALL
?