与JPA和EclipseLink在ManyToOne关系上的级联持续错误

时间:2013-11-20 09:37:42

标签: java spring jpa eclipselink

在EclipseLink中使用JPA我有2个类:用户和地址。

简化,在同一个事务中,我创建了一个新用户,一个新地址,并将该地址添加到用户,知道每个用户可以拥有多个地址:

User = new User();
Address address= new Address();
user.addAddress(address);

这是用户类中的映射:

@OneToMany(mappedBy = "idUser")
private Set<Address> addresses;

这是Address类中的映射:

@ManyToOne(cascade = { javax.persistence.CascadeType.REFRESH, javax.persistence.CascadeType.MERGE })
@JoinColumn(name = "id_user", referencedColumnName = "id", nullable = false)
private User user;

我正在使用Spring Data JPA Custom Repository,我注入了entitymanager并从服务中调用:

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);
} 

最后,当服务方法完成后,进行交易。

当我尝试提交该事件时,会出现错误:

'A new object was found through a relationship that was not marked cascade PERSIST'

如果我将用户地址列表标记为级联PERSIST,那么eclipselink会尝试将用户保存两次(我认为一个用户可以保留用户,第二个用户地址被保留)。

我怎样才能使eclipselink不再保留它,而是将其检测为现有对象?

PS:我试图使用merge而不是persist并且没有工作。

1 个答案:

答案 0 :(得分:4)

一个错误是:

@OneToMany(mappedBy = "user")//you have idUser

然后添加 请尝试以下方法:

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);