I have a @ManyToMany relationship between class A and class B : class A references a collection of class B instances, and this relationship is configured as CascadeType.ALL. So when a A is persisted with the entity manager, the B instances referenced by A are also persisted.
Both A and B have an ID declared with the GenerationType.IDENTITY strategy to use the auto_inc from the MySQL database.
The problem is :
=> JPA tries to persist the B objects though they are already persisted (they just have been loaded).
I don't understand why it tries to persist them again, they have been properly loaded, and their auto generated id has been well loaded as well.
The ManyToMany declaration :
@ManyToMany(cascade={CascadeType.ALL})
@JoinTable(name = "ENTRY_ENTITIES", joinColumns =
@JoinColumn(name = "ENTRY", referencedColumnName = "ID"),
inverseJoinColumns = @JoinColumn(name = "ENTITY", referencedColumnName = "ID"))
private List<Entity> entities;
The Query to load existing objects from database :
T result = (T) entityManager.createQuery("SELECT x FROM " + entityName + " x WHERE x.externalId='" + externalId + "'").getSingleResult();
The persisting :
UserTransaction transaction = getTransaction();
try {
transaction.begin();
entityManager.persist(entity);
transaction.commit();
} catch (Throwable t) {
Logger.getLogger(JpaDao.class.getName()).log(Level.SEVERE, null, t);
}
Thanks a lot for your help!
I'm not absolutely sure that this is the cause of your problem, but you should include the whole thing inside of a transaction. Not just the persistence part:
start transaction
load B from DB
create new A
add B to A
commit transaction
As I said in my comments, you have other design and coding problems:
SELECT x FROM A x WHERE x.externalId = :externalId
在将这些B实体添加到A时,这些B实体可能是另一个持久性上下文的一部分。您是否在开始事务之后是否尝试过在B实体上使用合并操作 , 然后再将它们添加到A实体中。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.