Annotation @Embedded et @Embeddable. From http://www.concretepage.com/hibernate/example-embeddable-embedded-hibernate-annotation
package com.concretepage.persistence;
import javax.persistence.Column;
import javax.persistence.Embeddable;
@Embeddable
public class Animal {
@Column(name = "name")
private String name;
@Column(name = "location")
private String location;
public Animal(){
}
public Animal(String name,String location){
this.name=name;
this.location=location;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
}
package com.concretepage.persistence;
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "elephant")
public class Elephant {
@Id
@Column(name = "id")
private int id;
@Embedded
@AttributeOverrides({ @AttributeOverride(name = "location", column = @Column(name = "place")) })
private Animal animal;
public Elephant(int id,Animal animal){
this.id=id;
this.animal=animal;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Animal getAnimal() {
return animal;
}
public void setAnimal(Animal animal) {
this.animal = animal;
}
}
package com.concretepage.persistence;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="lion")
public class Lion {
@Id
@Column(name = "id")
private int id;
@Embedded
private Animal animal;
public Lion(int id,Animal animal){
this.id=id;
this.animal=animal;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Animal getAnimal() {
return animal;
}
public void setAnimal(Animal animal) {
this.animal = animal;
}
}
Session session = getSession();
session.beginTransaction();
Animal animal = new Animal("Lion A", "Africa");
Lion lion = new Lion(1, animal);
animal = new Animal("Elephnat A", "Asia");
Elephant elephant = new Elephant(1, animal);
session.save(lion);
session.save(elephant);
session.getTransaction().commit();
session.close();