I'm trying to build a Hibernate layer for a database schema I have essentially no control over. Simplified, there are two tables.
Table parent
has two important columns:
parent_id
, integer, primary key, autoincrementedparent_code
, string, unique key, generated by a black box somewhere (let's say this is a UUID for sanity's sake)Table child
has two important columns:
child_parent_id
, integer, primary key, autoincrementedchild_parent_code
, string, foreign key pointing at the parent's parent_code
valueI want to be able to call Parent.getChilds() and get a Collection of Child objects. But setting up the Hibernate mapping files seems impossible. What it's doing with the mappings below is searching the child
table with the parent_id
value (instead of parent_code
).
In 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
:
<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. Is it possible?
The <many-to-one> element is used to set the relationship between EMPLOYEE and ADDRESS entities. The name attribute is set to the defined variable in the parent class, in our case it is address. The column attribute is used to set the column name in the parent table EMPLOYEE.
Description. Simply put, one-to-many mapping means that one row in a table is mapped to multiple rows in another table. For this example, we'll implement a cart system where we have a table for each cart and another table for each item. One cart can have many items, so here we have a one-to-many mapping.
Many-To-One relation between entities: Where one entity (column or set of columns) is/are referenced with another entity (column or set of columns) which contain unique values. In relational databases these relations are applicable by using foreign key/primary key between tables.
I would consider using the hibernate annotations. I found them to be MUCH easier to work with that the xml definitions.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With