简体   繁体   中英

JPA persists already persisted Objects from a ManyToMany relationship

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 :

  1. I create a new A
  2. I load some existing B objects from entityManager using JPQL
  3. I add the B objects to A's collection of Bs

=> 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:

  • CascadeType.ALL is wrong on a ManyToXxx association. You don't want all the Bs of an A deleted when you delete A, since those Bs are referenced by other As. This will lead to constraint violations (in the best case) or an inconsistent database (in the worst case, if you have no constraint defined)
  • Don't use string concatenation in your queries. Use parameterized queries. This will avoid quoting problems and injection attacks: 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM