views:

333

answers:

1

I'd like to configure this mapping with annotations instead of XML.

Here's the mapping config (sanitized for public consumption):

<hibernate-mapping package="com.test.model">
  <class name="Parent" table="parent">

    <composite-id name="id" class="ParentCompositeKey">
        <key-property name="first_id" type="long" column="first_id"/>
        <key-property name="second_id" type="long" column="second_id"/>
    </composite-id>     

    <set name="parentChildren" table="parent_child" inverse="true" cascade="all">
        <key on-delete="cascade">
            <column name="first_id"/>
            <column name="second_id"/>
        </key>
        <one-to-many class="Child" />
    </set>

  </class>
</hibernate-mapping>

Parent has a composite primary key consisting of two Longs. Child has a composite primary key consisting of the parent's composite primary key and an additional Long. When I remove a Parent, the intent is to also remove the related Child records. (These kids just can't fend for themselves, apparently.)

This is a unidirectional relationship. On the Child side, I have no need to find out the Parent.

I'm a bit of a beginner at JPA annotations. I've looked in the docs and tried various combinations of @OneToMany and @JoinTable with @JoinColumns to solve my problem thus far.

This question doesn't fill me with hope, but I figure if it works in XML, it ought to be doable with annotations.

Any advice appreciated.

+2  A: 

Here's a link to Hibernate Annotations documentation that covers most of what you want. The resulting mapping would be something along the lines of:

@Embeddable
public class ParentCompositeKey implements Serializable {

  public long getFirstId() { ... }

  public long getSecondId() { ... }

  // setters
}

@Entity
public class Parent implements Serializable {

  @Id
  public ParentCompositeKey getId() { ... }

  @OneToMany(cascade=CascadeType.ALL)
  @JoinColumns ({
        @JoinColumn(name="first_id"),
        @JoinColumn(name="second_id")
    })
  public List getParentChildren() { ... }

  // setters 
}

This assumes you have no join table (it's a bit unclear from your naming scheme whether you do). If you do, though, you just need to add a @JoinTable annotation and move @JoinColumns within it.

ChssPly76
Thanks. This really helped.
Kevin