I am attempting to develop a Hibernate layer for any database schema I've basically no treatments for. Simplified, you will find two tables.

Table parent has two important posts:

  • parent_id, integer, primary key, autoincremented
  • parent_code, string, unique key, produced with a black box somewhere (let us say this can be a UUID for sanity's sake)
  • Plus a lot of posts of information

Table child has two important posts:

  • child_parent_id, integer, primary key, autoincremented
  • child_parent_code, string, foreign key pointing in the parent's parent_code value
  • Plus a lot of posts of information

I wish to have the ability to call Parent.getChilds() and obtain an accumulation of Child objects. But establishing the Hibernate mapping files appears impossible. How it is doing using the mappings below is searching the child table using the parent_id value (rather than 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 have spent an hour or so poring through my copy of Java Persistence with Hibernate, however i can't learn how to do things i want. Is it feasible?

I'd think about using the hibernate annotations. I discovered these to considerably simpler to utilize 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;
}

Try something similar to this within 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>

which within the child:

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

I've assumed the code property within the parent is known as "code".