开发者

Hibernate - One design problem

I am learning Hibernate from the tutorials on JBoss website. I have a confusion in a code example located here.

There is a Cat class code at 4.1. A simple POJO example.

This Cat cla开发者_如何学Css has a reference to his mother as private Cat mother;

Q1. If the class has an identifier property as id, then wouldn't it be better to store the cat's mother's id instead of cat's mother object.

means instead of

private Cat mother;

wouldn't it be better to have

private long motherId; 

`


That's what hibernate implicitly does for you.

The good thing about ORM is that it completely hides implementation caveats due to the fact that you are working on a RDBMS instead that with plain objects. You can use mother as Cat without bothering about the fact that its relation it's expressed by an id internally.


Not necessarily, storing an object reference as opposed to an Id is beneficial because it implicitly validates the reference where as an Id could be any number, valid Cat Id or other. It's an extra layer of validate and error checking you have to handle.

The only pitfall you have to be wary of is serializing the object and ensuring that there is no infinite loops and Dto's can help there. For example, say you want to serialize Cat to a webservice and you only want to serialize a single cat not the entire cat hierarchy (Cat, Cat's Mother, Cat's Mother's Mother, etc). You could create a Data Transfer Object which is a thin wrapper around the Car class, this wrapping can serialize the Id instead of the referenced object so that consuming users can get the Mother if they want. Dto's have other benefits such as maintaining a constant interface while underlying domain objects can change to best suit the code base.


and beyond the reasons stated above, how about simple ease of use ? if i want to traverse a family tree using your design, the code would look something like:

Cat firstCat = //get starting cat somehow
Object someBroker = //get a 3rd party broker (like an entity manager)
Cat parent = broker.getCatById(firstCat.getParentId());

using actual Object references while be more elegant:

Cat firstCat = // get initial cat
while ((Cat ancestor = firstCat.getParent)!=null) {
   //work with ancestor
}

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜