Hibernate保存外键列的空值

时间:2018-02-06 04:46:08

标签: mysql hibernate save many-to-one

我与表部门的员工关系多与一个

CREATE TABLE `tbl_employee` (
  `employees_id` int(11) NOT NULL AUTO_INCREMENT,
  `employees_name` varchar(20) NOT NULL,
  `tbl_department_` int(11) DEFAULT NULL,
  PRIMARY KEY (`persion_id`)
)

将新数据添加到employee表时,如果我输入tbl_department_id的值为null,则会出现错误

我与表部门的员工关系多与一个

CREATE TABLE `tbl_employee` (
  `employees_id` int(11) NOT NULL AUTO_INCREMENT,
  `employees_name` varchar(20) NOT NULL,
  `tbl_department_` int(11) DEFAULT NULL,
  PRIMARY KEY (`persion_id`)
)

将新数据添加到employee表时,如果我输入tbl_department_id的值为null,则会出现错误

public class NewClass {
    public static void main(String[] args) {
        SessionFactory sessionFactory = NewHibernateUtil.getSessionFactory();
        Session currentSession = sessionFactory.getCurrentSession();
        currentSession.getTransaction().begin();

        TblDepartment tblDepartment = new TblDepartment();
        tblDepartment.setDepartmentId(null);

        TblEmployee tblEmployee = new TblEmployee();
        tblEmployee.setEmployeeName("");
        tblEmployee.setTblDepartment(tblDepartment);

        currentSession.save(tblEmployee);
        currentSession.getTransaction().commit();
    }
}

Exception in thread "main" org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: sf.enforcement.mavenproject1.TblDepartment
    at org.hibernate.engine.internal.ForeignKeys.getEntityIdentifierIfNotUnsaved(ForeignKeys.java:294)
    at org.hibernate.type.EntityType.getIdentifier(EntityType.java:510)
    at org.hibernate.type.ManyToOneType.nullSafeSet(ManyToOneType.java:174)
    at org.hibernate.engine.query.spi.NativeSQLQueryPlan.bindNamedParameters(NativeSQLQueryPlan.java:162)
    at org.hibernate.engine.query.spi.NativeSQLQueryPlan.performExecuteUpdate(NativeSQLQueryPlan.java:219)
    at org.hibernate.internal.SessionImpl.executeNativeUpdate(SessionImpl.java:1306)
    at org.hibernate.internal.SQLQueryImpl.executeUpdate(SQLQueryImpl.java:389)
    at sf.enforcement.mavenproject1.NewClass2.main(NewClass2.java:30)

我看到一个类似的问题由使用处理 CascadeType.ALL,CascadeType.SAVE_UPDATE

object references an unsaved transient instance - save the transient instance before flushing

我试图效仿,但失败了。 Hibernate版本4.3.1中不存在CascadeType.SAVE_UPDATE

@ManyToOne(fetch=FetchType.LAZY,cascade = CascadeType.ALL)
    @JoinColumn(name="tbl_department")
    public TblDepartment getTblDepartment() {
        return this.tblDepartment;
    }

我的POM

<dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>4.3.1.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.1-api</artifactId>
            <version>1.0.0.Final</version>
        </dependency>

如何使用外键在表中保存空值?请帮帮我

0 个答案:

没有答案