Hibernate OneToMany Example with CompoundKey

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

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

    a) Foreign key to the parent table ( foo_id )

    b) key ( item ) of type string

  • There is one parent for many children
  • The Parent class will have a list of child objects.
  • When the Parent class is saved, updated, deleted, the changes will be cascaded in Child
+4
source share
2 answers

I have not done exactly what you are asking for, but it can lead you in the right direction. I think this should work. This page explains these annotations in more 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() } 
+4
source

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>(); 

}

Note. @CollectionOfElements and IndexColumn are Hibernate annotations, not JPA 1.0. 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 work fine

Parent parent = new parent ();

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

session.save (parent); // Parent And Two Children Will Be Saved

The disadvantage of this problem is that the @CollectionOfElements annotation applies only to the @Embeddadble class, not to the Entity class. If you want the Child class as an Entity class, I would like to see a solution. At the same time, this is not possible. @Entity and @Embeddable class annotations.

Relations Arthur Ronald F. D. Garcia (Java Programmer) Natal / RN - Brazil

0
source

Source: https://habr.com/ru/post/1286373/


All Articles