在ManyToOne关系上,JPA和EclipseLink的级联持续错误 [英] Cascade persist error with JPA and EclipseLink on ManyToOne relationship
问题描述
将JPA与EclipseLink一起使用我有2个类:用户和地址.
Using JPA with EclipseLink I have 2 classes: User and Address.
简化一下,在同一笔交易中,我创建了一个新用户,一个新地址,并将该地址添加到该用户,因为每个用户可以有许多地址:
Simplifying, in the same transaction I creates a new user, a new address and add that address to the user knowing that each user can have many addresses:
User = new User();
Address address= new Address();
user.addAddress(address);
这是User类中的映射:
This is the mapping in User class:
@OneToMany(mappedBy = "idUser")
private Set<Address> addresses;
这是Address类中的映射:
This is the mapping in Address class:
@ManyToOne(cascade = { javax.persistence.CascadeType.REFRESH, javax.persistence.CascadeType.MERGE })
@JoinColumn(name = "id_user", referencedColumnName = "id", nullable = false)
private User user;
我使用的是Spring Data JPA自定义存储库,其中注入了objectmanager并从服务中调用它:
I am using a Spring Data JPA Custom Repository where I inject the entitymanager and is called from a service:
public void saveUser(TUsuario user)
{
em.persist(user);
}
之后,我坚持住地址
address.setDay(1);
address.setMonth(2);
address.setYear(3);
address.setUser(user);
public void saveUserAddress(Address address)
{
em.persist(address);
}
最后,当服务方法完成时,就完成了交易.
And finally, when the service method has finished, the transaction is made.
当我尝试进行thansaction时,会引发错误:
When I try to commit the thansaction an error raises:
'A new object was found through a relationship that was not marked cascade PERSIST'
如果我将用户地址列表标记为层叠PERSIST,则eclipselink尝试将用户保存两次(我认为当我保留用户时一个,而第二次当用户地址保留时).
If I mark the user addresses list as cascade PERSIST, then eclipselink tries to save the user twice (I think one when I persist the user and second when the user address is persisted).
我该怎么做才能使eclipselink不持久化,而是将其检测为现有对象?
How can I do it to eclipselink not to persist it, but detect it as an existing object?
PS:我尝试使用merge而不是persist,但没有用.
PS: I tried to use merge instead of persist and didn't work.
推荐答案
一个错误是:
@OneToMany(mappedBy = "user")//you have idUser
然后添加 请尝试以下操作:
Then add Try the following:
User user = new User();
Address address = new Address();
address.setUser(User);
user.addAddress(address);
em.persist(user);//you can delete this, if you add PERSIST (address.user field) to the @ManyToOne(cascade = { javax.persistence.CascadeType.REFRESH, javax.persistence.CascadeType.MERGE })
em.persist(address);
这篇关于在ManyToOne关系上,JPA和EclipseLink的级联持续错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!