Tutorial :Hibernate Example OneToMany with compositeKey



Question:

Can you give me an example of a Hibernate mapping for the following situation:

  1. Parent table(foo) with a simple primary key (foo_id)
  2. child table(bar) with a composite key consisting of

    a) Foreign key to parent table (foo_id)

    b) key(item) of type string

  3. There is one parent to many child
  4. The Parent class will have a list of Child objects
  5. When a Parent class is saved, updated, deleted the changes will cascade to the Child


Solution:1

I haven't done exactly what you are asking for but this might start you off in the right direction. I think it should work. This page explains these annotations in greater detail.

@Entity  public class Foo {        @Id      @GeneratedValue(strategy=GenerationType.AUTO)      public Long getId(){        }      ...      @OneToMany(mappedBy="foo")      public Collection<Bar> getBars() {        }      ...  }      @Entity  @IdClass(BarPk.class)  public class Bar implements Serializable {      @ManyToOne      @JoinColumn(name="foo")      @Id      public Foo getFoo() {          return foo;      }        @Column(name="key", length=255)      @Id      public String getKey(){        }    }      @Embeddable  public class BarPk implements Serializable {      public Foo getFoo() {          return foo;      }      public void setFoo(Foo foo) {        }      public String getKey(){      ...      }           public void setKey(String key){      ...      }             //you must include equals() and hashcode()      }  


Solution:2

Yes, you should use the following mapping

@Entity public class Parent {

@Id  private Integer id;    @CollectionOfElements  @JoinTable(      name="Child",      joinColumn=@JoinColumn(name="PARENT_ID"))  @IndexColumn("childIndex")  private List<Child> childList = new ArrayList<Child>();  

}

Notice @CollectionOfElements and IndexColumn is Hibernate specific annotations, not JPA 1.0 specification. JPA 2.0 will introduce them.

@Embeddable public class Child {

// @Embeddable class does not contains identifiers   // child class specific property's  

}

So the following code will works fine

Parent parent = new Parent();

parent.getChildList().add(new Child()); parent.getChildList().add(new Child()); // other child

session.save(parent); // A parent and two children will be saved

The drawback with this issue is that @CollectionOfElements annotation only applies to @Embeddadble class, not a Entity class. If you want a Child class as a Entity class, i would like to see the solution. It is not possible applies at the same time @Entity and @Embeddable annotations to a class.

Regards Arthur Ronald F D Garcia (Java programmer) Natal/RN - Brazil


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »