【问题标题】:Hibernate: Specifying columns in a one-to-many relationshipHibernate:以一对多关系指定列
【发布时间】:2010-11-06 04:40:34
【问题描述】:

我正在尝试为我基本上无法控制的数据库模式构建 Hibernate 层。简单来说,有两张表。

parent有两个重要的列:

  • parent_id,整数,主键,自增
  • parent_code,字符串,唯一密钥,由某处的黑匣子生成(为了理智,假设这是一个 UUID)
  • 加上一堆数据列

child有两个重要的列:

  • child_parent_id,整数,主键,自增
  • child_parent_code,字符串,外键指向父级的parent_code
  • 加上一堆数据列

我希望能够调用 Parent.getChilds() 并获得 Child 对象的 Collection。但是设置 Hibernate 映射文件似乎是不可能的。它对以下映射的作用是使用 parent_id 值(而不是 parent_code)搜索 child 表。

Parent.hbm.xml:

    <set name="childs" inverse="true" lazy="true" table="child" fetch="select">
        <key>
            <column name="child_parent_code" not-null="true" />
        </key>
        <one-to-many class="foo.bar.Child" />
    </set>

Child.hbm.xml:

    <many-to-one name="parent" class="foo.bar.Parent" fetch="select">
        <column name="child_parent_code" not-null="true" />
    </many-to-one>

我花了一个小时仔细研究我的Java Persistence with Hibernate,但我不知道如何做我想做的事。有可能吗?

【问题讨论】:

    标签: java database hibernate schema


    【解决方案1】:

    我会考虑使用休眠注释。我发现它们更容易使用 xml 定义。

    这是注释格式的代码:

    @Entity
    @Table(name="parent")
    public class Parent
    {
    
        @Id
        @GeneratedValue(strategy=GenerationType.IDENTITY)
        private int id;
    
        @ManyToOne
            @JoinColumn(name="child", referencedColumnName = "id")
        private Child child;
    }
    
    @Entity
    @Table(name = "child")
    public class Child
    {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        public int id;
    
        @Column(name = "code")
        public String code;
    }
    

    【讨论】:

    • 这与实际问题无关吗?
    • 它是相关的,我个人觉得它很有帮助。
    【解决方案2】:

    在父母中尝试这样的事情:

    <set name="childs" inverse="true" lazy="true" table="child" fetch="select">
        <key column="child_parent_code" property-ref="code" />
        <one-to-many class="foo.bar.Child" />
    </set>
    

    这在孩子身上:

    <many-to-one name="parent" class="foo.bar.Parent"
        fetch="select" column="child_parent_code" property-ref="code" />
    

    我假设父级中的代码属性称为“代码”。

    【讨论】:

    • @DavidM hibernate中是否有property-ref等价注解?
    猜你喜欢
    • 2021-02-16
    • 1970-01-01
    • 2015-03-29
    • 2015-02-05
    • 2018-11-09
    • 2011-12-15
    • 2011-09-30
    • 1970-01-01
    • 2020-12-26
    相关资源
    最近更新 更多