简体   繁体   中英

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. One Employee can have several Jobs, but a Job can only have a single Employee.

I used Liquibase to build my database. 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.

Here are the relevant parts of the Employee and Job classes:

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:

@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):

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? Or did I mess something up with 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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