【问题标题】:Unidirectional OneToMany with Foreign key doesn't insert to table具有外键的单向 OneToMany 不会插入到表中
【发布时间】:2013-07-07 05:00:40
【问题描述】:

我有以下课程:

@Entity
@Table(name = "PARENT")
public class Parent {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "PARENT_ID", unique = true, nullable = false, insertable = true, updatable = true)
private Long parentId;


@OneToMany(cascade = {CascadeType.ALL}, fetch = FetchType.EAGER ) 
@JoinColumn(name="PARENT_ID", nullable = false)
private List<Child> children;


public Parent(List<Child> children) {
this.children = children;
}


..
... Getters\Setters

}


@Entity
@Table(name = "CHILD")
public class Child {

@Id 
@Column(name = "TYPE", unique = false, nullable = false)
private String type;

@Column(name = "RANK", unique = false, nullable = false, insertable = true, updatable = false)
private String rank;

}

“PARENT_ID”是“CHILD”表中的外键。所以它使“CHILD”表有 2 列形成其 PRIMARY_KEY。

我执行以下插入:

List<Child> children = new LinkedList<Child>();
children.add(new Child("1,2,3,4"));
children.add(new Child("1,2,3,4"));

Parent parent = new Parent(children);

session.save(parent);

如果两个表都是空的,它会通过分配 PARENT_ID 正确地创建“父”和“子”!但是如果表中已经存在“子”条目,它会执行更新而不是插入!

请注意,两个 'child' 具有相同的“TYPE”(“1,2,3,4”),但它们应该具有不同的“PARENT_ID”。

我在这里错过了什么????

谢谢!

【问题讨论】:

    标签: hibernate hibernate-mapping hibernate-onetomany


    【解决方案1】:

    在您的孩子中,您需要有一个父级的实例,我相信您在您的 Parent 类中放错了 JoinColumn,它应该在您的子类中。而且您的 Parent 类中不需要构造函数。

    父类应该类似于:

    @Entity
    @Table(name = "PARENT")
    public class Parent {
    
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "PARENT_ID", unique = true, nullable = false, insertable = true,          updatable = true)
    private Long parentId;
    
    
    @Embedded
    private Child children;
    
    
    ..
    ... Getters\Setters (MAke sure you have the getter setter for children as well)
    
    }
    

    你的 Child 类应该是这样的:

    @Embeddable
    @Table(name = "CHILD")
    public class Child {
    
    @Id 
    @Column(name = "TYPE", unique = false, nullable = false)
    private String type;
    
    @Column(name = "RANK", unique = false, nullable = false, insertable = true, updatable = false)
    private String rank;
    
    
        //getter and setters
    

    【讨论】:

    • 是的,这可能行得通,但现在它是双向关联,这很好,但给代码增加了不必要的复杂性。
    • 是的,你可能是对的,Embedded 和 Embeddable 可能是更好的方法。但是,您将使用它的上下文将更重要
    猜你喜欢
    • 1970-01-01
    • 2011-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-26
    • 1970-01-01
    • 2017-05-23
    相关资源
    最近更新 更多