小编典典

Hibernate异常:分离实体已传递以持久化

hibernate

我正在尝试使用Hibernate EntityManagerpersist方法将个人pojo插入mysql db,

entityManagerTransactionService.getEntityManager().persist(TemplateObject);

得到这个例外

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

还有更多..

 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)

我的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;
        @OneToOne(cascade = { CascadeType.ALL })
        private Country country;

然后是pojo的getter setter方法。

引发TitleType类的错误是“公共静态最终”标题类型定义提供程序,

@Entity
public class TitleType extends TemplateObject {

    /**
     * 
     */
    private static final long serialVersionUID = 3104954552111621034L;

    private TitleType(int id, String name) {
        setId(id);
        setName(name);
    }

    public static final TitleType MR = new TitleType(1, "Mr");
    public static final TitleType MISS = new TitleType(2, "Miss");
    public static final TitleType MRS = new TitleType(3, "Mrs");
    public static final TitleType MS = new TitleType(4, "Ms");
    public static final TitleType DOCTOR = new TitleType(5, "Doctor");
    public static final TitleType PROFESSOR = new TitleType(6, "Professor");
    public static final TitleType SIR = new TitleType(7, "Sir");
    public static final TitleType MADAM = new TitleType(8, "Madam");

}

我正在为人员设置标题类型类,

person.setTitleType(TitleType.MR);

不可能将公共静态最终类型定义的类传递给Hibernate?还是我做错了什么?

提前致谢


阅读 365

收藏
2020-06-20

共1个答案

小编典典

您尝试保留的对象TitleType应该没有ID值。否则,Hibernate将检查该对象在会话上下文中是持久的还是分离的。如果您不想像这样持久化对象的某些字段,则可以@Transient在持久化实体时使用批注从字段映射中排除这些字段。这对于在DAO或实体中对ID进行硬编码是不好的,因为这些值可以由某些生成器生成,但是如果您使用此常数手动更新数据库,则可以至少将这些ID定义为代码中的常数,并通过ID从会话中加载对象在初始化临时或持久实例之前。

2020-06-20