org.hibernate.PersistentObjectException:传递给persist的分离实体:com.hibernate.dto.Employee

时间:2017-02-08 10:28:47

标签: hibernate

我的Employee课程如下,OneToMany与Education的关系

@Entity
    public class Employee {
        @Id
        @GeneratedValue
        private int empId;
        private String empName;
        @Temporal(TemporalType.DATE)
        private Date empDob;
        @Temporal(TemporalType.TIMESTAMP)
        private Date empDoj;
        private Long empPhone;
        @OneToMany(cascade=CascadeType.PERSIST)

       //setter and getters
}

@Entity
public class Education {
   @Id
    @GeneratedValue
    private Integer aadharNum;
    private String collegeName;
    private String schoolName;
    private String companyName;

    // setter and getter

}
        public class HibernateTest {
                public static void main(String[] args) {
                try {
                    Employee employee=new Employee();
                    employee.setEmpName("Sri");
                    employee.setEmpId(7664);
                    employee.setEmpDob(new java.util.Date());
                    employee.setEmpDoj(new java.util.Date());
                    employee.setEmpPhone(8102087655l);
                    Education education=new Education();
                    education.setSchoolName("Neo Royal School");
                    education.setCollegeName("IIT Gu");
                    education.setCompanyName("Insys");
                    Education education2=new Education();
                    education2.setSchoolName("Royal School");
                    education2.setCollegeName("IIT Hyd");
                    education2.setCompanyName("IM");
                    employee.getEducation().add(education);
                    employee.getEducation().add(education2);

    SessionFactory sessionFactory=new Configuration().configure().buildSessionFactory();
                    Session session=sessionFactory.openSession();
                    session.beginTransaction();
                    session.persist(employee);
                    session.getTransaction().commit();
                    session.close();
        } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

2 个答案:

答案 0 :(得分:0)

这是因为您手动为您的员工实体分配了一个尚未由Hibernate管理的ID。 删除此employee.setEmpId(7664);时它应该有效 然后,Hibernate将为您自动生成ID(因为@GeneratedValue)。

答案 1 :(得分:0)

问题是,对于你的empId,你正在使用@GeneratedValue注释。这意味着当你持久化一个新实体时,id字段应该留空,你必须让jpa提供者填写它。

所以要么删除@GeneratedValue

@Id
private int empId;

或者不要明确设置empId

相关问题