简体   繁体   English

Spring-Hibernate:插入错误,非空约束(一对多关系)

[英]Spring-Hibernate: Insertion error, not-null constraint (One-to-many relationship)

I've been at this for a while and I can't find where I'm going wrong. 我已经有一段时间了,但我找不到我要去哪里。 I assume that it is some minor and/or simple error and a second pair of eyes will probably find it quickly. 我认为这是一个较小和/或简单的错误,第二双眼睛可能会很快找到它。

I'm building a MySQL db consisting of Employees and Jobs. 我正在建立一个由员工和工作组成的MySQL数据库。 One Employee can have several Jobs, but a Job can only have a single Employee. 一个雇员可以有多个工作,但是一个工作只能有一个雇员。

I used Liquibase to build my database. 我使用Liquibase构建数据库。 Here are my changesets: 这是我的变更集:

<changeSet id="0001" author="mparker" context="base">
    <comment>Creating Base Table</comment>
    <createTable tableName="employees" >
        <column name="employeeID" autoIncrement="true" type="int">
            <constraints primaryKey="true" nullable="false"/>
        </column>
        <column name="firstname" type="varchar(50)">
            <constraints nullable="false"/>
        </column>
        <column name="lastname" type="varchar(50)">
            <constraints nullable="false"/>
        </column>
    </createTable>
</changeSet>
<changeSet id="0002" author="mparker">
    <createTable tableName="jobs" >
        <column name="jobID" autoIncrement="true" type="int">
            <constraints primaryKey="true" nullable="false"/>
        </column>
        <column name="employer" type="varchar(50)">
            <constraints nullable="false"/>
        </column>
        <column name="employeeID" type="int">
            <constraints nullable="false"/>
        </column>
    </createTable>
</changeSet>

As you can see, I am trying to create two tables where each entry has its own unique identifier that auto-increments when a new entry is added to the table. 如您所见,我正在尝试创建两个表,其中每个条目都有自己的唯一标识符,当将新条目添加到表时,该标识符会自动递增。 These columns should never be null, because the value should just be the previous value + 1. 这些列绝不能为空,因为该值应仅为前一个值+ 1。

Here are the relevant parts of the Employee and Job classes: 以下是Employee和Job类的相关部分:

Employee.java: Employee.java:

@Entity
@Table(name = "employees")
public class Employee {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "employeeID")
    private Long id;

    @Column(name = "firstname")
    private String firstName;

    @Column(name = "lastname")
    private String lastName;
    @OneToMany(mappedBy = "employee", cascade = CascadeType.PERSIST, fetch = FetchType.LAZY)
    private List<Job> jobList = new ArrayList<Job>();

    // getters and setters...
}

Job.java: Job.java:

@Entity
@Table(name = "jobs")
public class Job {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "jobID")
    private Long id;

    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)
    @JoinColumn(name = "employeeID")
    private Employee employee;

    @Column(name = "employer")
    private String employer;

    // getters and setters...

}

And the method used to save an employee (using an autowired EntityManager): 以及用于保存员工的方法(使用自动连接的EntityManager):

public void saveEmployee(String firstname, String lastname, List<Job> jobs) {
    Employee employee1 = new Employee();
    employee1.setJobList(jobs);
    employee1.setFirstName(firstname);
    employee1.setLastName(lastname);
    entityManager.persist(employee1);
}

Here is the exception thrown when executing this method: 这是执行此方法时引发的异常:

[ERROR] 2014-08-14 11:33:51,561 org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions - Column 'employeeID' cannot be null
[ERROR] 2014-08-14 11:33:51,603 com.sourceallies.webapp.exceptions.CustomHandlerExceptionResolver resolveException - could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement

I'm at a loss as to what could be causing this. 我不知道可能是什么原因造成的。 Shouldn't employeeID be generated upon each entry? 不应在每次输入时生成employeeID吗? Or did I mess something up with Hibernate? 还是我把Hibernate弄乱了?

Thanks! 谢谢!

Figured it out. 弄清楚了。

My save function should have assigned the employee I was creating to each job: 我的保存功能应已将我创建的员工分配给每个工作:

public void saveEmployee(String firstname, String lastname, List<Job> jobs) {
    Employee employee1 = new Employee();
    employee1.setFirstName(firstname);
    employee1.setLastName(lastname);
    for (Job job : jobs) {
        job.setEmployee(employee1);
    }
    employee1.setJobList(jobs);
    entityManager.persist(employee1);
}

I also needed to add a foreign key constraint to my employeeID column in my jobs table: 我还需要向我的工作表中的employeeID列添加外键约束:

<changeSet id="0003" author="mparker">
    <addForeignKeyConstraint 
        baseTableName="jobs"
        baseColumnNames="employeeID"
        constraintName="FK_jobs_employeeID_employees_employeeID"
        referencedTableName="employees"
        referencedColumnNames="employeeID"/>
</changeSet>

Thanks for the suggestions, everyone. 谢谢大家的建议。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM