To represent this relation in Hibernate we insert into Person a List of Attribute and annotate the getter as shown here:
@Entity
@Table(name = "person")
class Person{
private Long id;
[...]
private List attributes;
@OneToMany(fetch = FetchType.LAZY)
@JoinColumn(name="person_id")
List getAttributes(){
return this.attributes;
}
}
Attribute itself is not shown here because we are only interested in the id of the Attribute and the value "attributeComment" of the relationship between Person and Attribute.
The relationship called AttributeMatrix is shown here:
@Entity
@Table(name = "attributematrix")
public class AttributeMatrix
AttributeMatrixPrimaryKey attributeMatrixPK;
String attributeComment;
@Id
AttributeMatrixPrimaryKey getAttributeMatrixPK(){
return this.attributeMatrixPK;
}
We need an extra class for the primary key because it consists of multiple columns and we do that by annotating it as @Embeddable and implementing the Serializable-Interface.
@Embeddable
public class AttributeMatrixPrimaryKey implements Serializable {
private Long personId;
private Long attributeId;
@Column(name = "person_id")
public Long getPersonId() {
return personId;
}
@Column(name = "attribute_id")
public Long getAttributeId() {
return attributeId;
}
}
In our persistence-layer we implement a method that delivers us an instance of the class Person by PersonId.
public Person getPersonById(Long personId) {
Person person = (Person)getHibernateTemplate().get(Person.class,personId);
return person;
}
Since we got the instance of our class Person we could perform several operations on Person like reading the name.
/**
* Some Javadoc
*/
public List getPersonWithAttributes(Long personId) throws PersonServiceException {
Person person = persistenceLayer.getPersonById(personId);
if("crusoe".equals(person.getLastname()){
System.out.println("Hooray, Mr Crusoe has been found");
}
But in the moment we try to access the "List
/**
* Some Javadoc
*/
@Transactional(propagation = Propagation.NESTED, rollbackFor = PersonServiceException.class)
public List getPersonWithAttributes(Long personId) throws PersonServiceException {
[....]
In this case Spring leaves the Hibernate-session open for the duration of the method getPersonWithAttributes(Long personId) and Hibernate can now lazy-fetch the list of the Attributes.
Technorati Tags: spring hibernate session
