mapping objects
ok lets discuss how object can be persist and retrieve
at least two things need to be taken under account writing your entities
- direction in relationships – take a look. And a good example showing relations between objects http://java.boot.by/scbcd5-guide/ch05s04.html. Notice how each relation is mapped to DB.And something interesting about hibernate, thing I was so confused about. (I’ve took it form one of polish google group so If you are interested in whole post go to http://groups.google.com/group/pl.comp.lang.java/brows)
“Transparent POJO-oriented persistence implementations such as Hibernate do not implement managed associations. Contrary to CMR, Hibernate associations are all inherently unidirectional.”
following the author, Hibernate is not too clever and can’t figure out that objects are related in both way, we should assign them manualy, and he is advising simple code like this
@Entity class Company { ... public void addEmployee(Employee empl) { getEmployees().add(empl); empl.setCompany(this); } } - fetching style – lazy or eager – defined in your
@OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY)
annotation. Main difference is when collection of your related entity is created. One important thing to remember is that each fetch operation is within transaction. After that transaction success and your fetch type is lazy, you can’t get collection of related objects. One solution is to fetch with eager type but this makes a lot of sql selects to your DB and you use more memory for your objects. It doesn’t matter for 1000 records in your DB but over 10000 it can make a difference.
As far as I’m concerned better way is to lazy fetch and then use em.merge(object) method on object that is currently outside transaction. the method will set all related collection.