views:

666

answers:

2

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, autoincremented
  • parent_code, string, unique key, generated by a black box somewhere (let's say this is a UUID for sanity's sake)
  • Plus a bunch of columns of data

Table child has two important columns:

  • child_parent_id, integer, primary key, autoincremented
  • child_parent_code, string, foreign key pointing at the parent's parent_code value
  • Plus a bunch of columns of data

I 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?

+1  A: 

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;
}
Jesse
This isn't relevant to the actual question is it?
David M
+1  A: 

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".

David M
The property-ref attribute totally worked. Thanks!
Plutor
No problem, glad it helped.
David M