[英]Hibernate: Specifying columns in a one-to-many relationship
I'm trying to build a Hibernate layer for a database schema I have essentially no control over. 我正在尝试为数据库模式构建一个Hibernate层,我基本上无法控制。 Simplified, there are two tables.
简化后,有两个表。
Table parent
has two important columns: 表
parent
有两个重要的列:
parent_id
, integer, primary key, autoincremented parent_id
,整数,主键,自动增量 parent_code
, string, unique key, generated by a black box somewhere (let's say this is a UUID for sanity's sake) parent_code
,string,unique key,由某个黑盒子生成(让我们说这是一个UUID,为了理智) Table child
has two important columns: 表
child
有两个重要的列:
child_parent_id
, integer, primary key, autoincremented child_parent_id
,整数,主键,自动增量 child_parent_code
, string, foreign key pointing at the parent's parent_code
value child_parent_code
,string,指向父级parent_code
值的外键 I want to be able to call Parent.getChilds() and get a Collection of Child objects. 我希望能够调用Parent.getChilds()并获取Child对象的集合。 But setting up the Hibernate mapping files seems impossible.
但是设置Hibernate映射文件似乎是不可能的。 What it's doing with the mappings below is searching the
child
table with the parent_id
value (instead of parent_code
). 它使用下面的映射做的是使用
parent_id
值(而不是parent_code
)搜索child
表。
In Parent.hbm.xml
: 在
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>
In Child.hbm.xml
: 在
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>
I've spent an hour poring through my copy of Java Persistence with Hibernate , but I can't figure out how to do what I want. 我花了一个小时仔细阅读我的Java Persistence with Hibernate副本,但我无法弄清楚如何做我想做的事情。 Is it possible?
可能吗?
I would consider using the hibernate annotations. 我会考虑使用hibernate注释。 I found them to be MUCH easier to work with that the xml definitions.
我发现它们更容易使用xml定义。
Here's the code in annotation format: 这是注释格式的代码:
@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;
}
Try something like this in the parent: 在父母中尝试这样的事情:
<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>
and this in the child: 这在孩子身上:
<many-to-one name="parent" class="foo.bar.Parent"
fetch="select" column="child_parent_code" property-ref="code" />
I have assumed that the code property in the parent is called "code". 我假设父代码中的代码属性称为“代码”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.