Java – how to cascade and keep only new entities

I am not sure how to set JPA persistence correctly for the following entities (using eclipse link and transaction type = "resource_local"):

@Entity
public class User {
    // snip varIoUs members

    @ManyToMany
    private List<Company> companies;

    public void setCompanies(List<Company> companies) {
           this.companies = companies;
    }
}

@Entity
public class Company {
    // snip varIoUs members
}

What I want to do is set up a cascade for the company list, so that if a new company that has not been reserved before is in the list, it will automatically stay with the user:

User newUser = new User();

Company newCompany = new Company();
List<Company> companies = new ArrayList<Company>();
companies.add(newCompany);

newUser.setCompanies(companies);

entityManager.persist(newUser);

By setting cascadetype on @ manytomany Persist, it works well However, if a pre reserved company is included in the company list, I will receive a mysqlintegrityconstraintviolationexception because it attempts to use the same primary key to persist (insert) a new company:

User newUser = new User();

Company oldCompany = companyDAO.find(oldCompanyId);
List<Company> companies = new ArrayList<Company>();
companies.add(oldCompany);

newUser.setCompanies(companies);

entityManager.persist(newUser);

So how should I set it so that the new company is automatically retained, but the existing company is only added to the user company mapping?

Solution

The best way to consider cascading in Hibernate is that if you call method X on the parent, it will call method X on each child. So yes, if you make persistent calls to users, it will make persistent calls to each child whether they persist or not

This situation is not ideal for cascading Cascading persistence applies when all children are created using their parents (for example, if the user has a skill list), it is more used for one to many

I personally don't use cascading in this case Openly using cascading when it is not needed will slow down the application

If you think cascading is necessary, you can use level Federation and The merge will remain when the entity has not been persisted However, merger has some very strange side effects, which may be why you didn't notice it working Consider the following example:

x = new Foo();
y = new Foo();

em.persist(x);
Foo z = em.merge(y);

//x is associated with the persistence context
//y is NOT associated with the persistence context
//z is associated with the persistence context
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>