EntityManager.merge() 可以插入新对象并更新现有对象.
为什么要使用persist()(只能创建新对象)?
我有2个实体:Account和AccountRole.
public class Account {
private AccountRole accountRole;
@ManyToOne(cascade = CascadeType.PERSIST, fetch = FetchType.EAGER)
public AccountRole getAccountRole() {
return accountRole;
}
Run Code Online (Sandbox Code Playgroud)
.
public class AccountRole {
private Collection<Account> accounts = new ArrayList<Account>();
@OneToMany(mappedBy = "accountRole", fetch = FetchType.EAGER)
public Collection<Account> getAccounts() {
return accounts;
}
Run Code Online (Sandbox Code Playgroud)
当我从数据库中获取accountRole并试图坚持我的问题时出现问题Account.此时我刚创建了我的帐户,角色已经存在于db中.
AccountRole role = accountService.getRoleFromDatabase(AccountRoles.ROLE_USER);
account.setAccountRole(role);
//setting both ways, as suggested
public void setAccountRole(AccountRole accountRole) {
accountRole.addAccount(this);
this.accountRole = accountRole;
}
entityManager.persist(account); // finally in my DAO
Run Code Online (Sandbox Code Playgroud)
我读到这个: …
我正在尝试使用Hibernate EntityManager persist方法将一个人pojo插入mysql数据库,
entityManagerTransactionService.getEntityManager().persist(TemplateObject);
Run Code Online (Sandbox Code Playgroud)
得到这个例外,
javax.persistence.PersistenceException:
org.hibernate.PersistentObjectException: detached entity passed to
persist: com.esupu.base.model.pojo.common.TitleType at
org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1387)....
Run Code Online (Sandbox Code Playgroud)
还有更多......
Caused by: org.hibernate.PersistentObjectException: detached entity
passed to persist: com.esupu.base.model.pojo.common.TitleType at
org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:141)
at
org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:843)
Run Code Online (Sandbox Code Playgroud)
我的Person.java类是,
@Entity
public class Person extends TemplateObject {
@OneToOne(cascade = { CascadeType.MERGE, CascadeType.PERSIST,CascadeType.REFRESH })
private TitleType titleType;
private String middle;
private String last;
@OneToOne(cascade = { CascadeType.ALL })
private Address address;
private Date birthdate;
private String email;
private String telephone;
private String fax;
@OneToOne(cascade = { CascadeType.ALL })
private Location location; …Run Code Online (Sandbox Code Playgroud)