【问题标题】:Hibernate Example OneToMany with compositeKey使用 CompositeKey 的休眠示例 OneToMany
【发布时间】:2009-06-17 18:21:23
【问题描述】:

你能给我一个 Hibernate 映射的例子吗:

  1. 带有简单主键 (foo_id) 的父表 (foo)
  2. 子表(bar) 的复合键由

    a) 父表的外键 (foo_id)

    b) 字符串类型的键(item)

  3. 一个父母对多个孩子
  4. 父类将有一个子对象列表
  5. 保存、更新、删除父类时,更改将级联到子类

【问题讨论】:

    标签: java hibernate orm


    【解决方案1】:

    我还没有完全按照您的要求完成,但这可能会让您朝着正确的方向前进。我认为它应该工作。这个page 更详细地解释了这些注释。

    @Entity
    public class Foo {
    
        @Id
        @GeneratedValue(strategy=GenerationType.AUTO)
        public Long getId(){
    
        }
        ...
        @OneToMany(mappedBy="foo")
        public Collection<Bar> getBars() {
    
        }
    
    
    ...
    }
    
    
    @Entity
    @IdClass(BarPk.class)
    public class Bar implements Serializable {
        @ManyToOne
        @JoinColumn(name="foo")
        @Id
        public Foo getFoo() {
            return foo;
        }
    
        @Column(name="key", length=255)
        @Id
        public String getKey(){
    
        }
    
    }
    
    
    @Embeddable
    public class BarPk implements Serializable {
        public Foo getFoo() {
            return foo;
        }
        public void setFoo(Foo foo) {
    
        }
        public String getKey(){
        ...
        }   
    
        public void setKey(String key){
        ...
        }     
    
        //you must include equals() and hashcode()    
    }
    

    【讨论】:

    【解决方案2】:

    是的,您应该使用以下映射

    @实体 公共类家长{

    @Id
    private Integer id;
    
    @CollectionOfElements
    @JoinTable(
        name="Child",
        joinColumn=@JoinColumn(name="PARENT_ID"))
    @IndexColumn("childIndex")
    private List<Child> childList = new ArrayList<Child>();
    

    }

    注意 @CollectionOfElements 和 IndexColumn 是 Hibernate 特定的注释,而不是 JPA 1.0 规范。 JPA 2.0 将介绍它们。

    @Embeddable 公共类子{

    // @Embeddable class does not contains identifiers 
    // child class specific property's
    

    }

    所以下面的代码可以正常工作

    父父=新父();

    parent.getChildList().add(new Child()); parent.getChildList().add(new Child()); // 其他孩子

    session.save(父); // 一个父母和两个孩子将被保存

    这个问题的缺点是@CollectionOfElements 注解仅适用于@Embeddadble 类,不适用于Entity 类。如果您想要一个子类作为实体类,我想看看解决方案。 @Entity 和 @Embeddable 注解不能同时应用于一个类。

    问候 Arthur Ronald F D Garcia(Java 程序员) 纳塔尔/注册护士 - 巴西

    【讨论】:

      猜你喜欢
      • 2011-10-31
      • 2013-07-01
      • 1970-01-01
      • 2017-07-30
      • 1970-01-01
      • 2015-07-07
      • 2019-12-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多