【问题标题】:Cascade insert with JPA/Hibernate (EclipseLink)使用 JPA/Hibernate (EclipseLink) 的级联插入
【发布时间】:2011-11-23 07:51:52
【问题描述】:

我有两张这样的桌子

|      PERSON       |     |    EMPLOYEE     |
|  id  |  fullName  |     | personId | code |

EMPLOYEE.personId 是指向PERSON.id 的主键和外键

我有这两个类:

@Entity
@Table(name="PERSON")
@Inheritance(strategy=InheritanceType.JOINED)
public abstract class Person 
                  implements Serializable {
    protected int id;
    protected String fullName;

    @Id
    @Column("id")
    public int getId() {
         return this.id
    }

    public void setId(int id) {
        this.id = id;
    }

    @Column("fullName")
    public int getFullName() {
         return this.fullName
    }

    public void setId(int fullName) {
        this.fullName = fullName;
    }

}

@Entity
@Table(name="EMPLOYEE")
@PrimaryKeyJoinColumn(name="personId")
public class Employee extends Person
        implements Serializable {

    private String code;

    public Employee(String code) {
        setCode(code);
    }

    @Column("code")
    public String getCode() {
         return this.code
    }

    public void setCode(String code) {
        this.code = code;
    }

}

当我想在 EMPLOYEE 表中插入一条新记录时:

entityTransaction.begin();
Employee emp = new Employee("EMP001");
emp.setFullName("hiri");
this.entityManager.persist(emp);
entityTransaction.commit();

它抛出一个异常说:

Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (...)
Error Code: 1452
Call: INSERT INTO EMPLOYEE (code, personId) VALUES (?, ?)
    bind => [EMP001, 0]

如您所见,它应该先插入一个新的 Person 记录,然后再插入一个 Employee,但实际上并没有,外键 personId=0 导致了问题。你能帮助我吗?谢谢!

【问题讨论】:

    标签: hibernate jpa-2.0 eclipselink


    【解决方案1】:

    使用继承时不需要@PrimaryKeyJoinColumn。它将自动为您管理。不过,您确实需要有一个唯一的 ID 值。如果您打算使用序列生成,则需要将@GeneratedValue 添加到 id。

        @Id
        @GeneratedValue
        @Column("id")
        public int getId() {
            return this.id
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-12
      • 1970-01-01
      • 1970-01-01
      • 2011-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多