开发者

What's the point of having complex entity classes (in the Hibernate sense)

开发者 https://www.devze.com 2023-03-20 15:00 出处:网络
Since the classic OOP model is broken anyway, despite all the goodies of ORM, why do I need to annotate the following two example attributes in my entity class:

Since the classic OOP model is broken anyway, despite all the goodies of ORM, why do I need to annotate the following two example attributes in my entity class:

User
   => Collection<Photo> photos (one to many)
   => Collection<User> friends (one to many)

as I am not going to use those ... ever. Seemingl开发者_开发技巧y, I will need to do some paging or other types of formatting, so I guess I'll always go for something like:

photoDAOInstance.find(searchCriteria); 

Why don't I simply restrict the annotation of my entity classes to only the attributes which the corresponding database table contains? The rest would be just transient properties.


Well, if you never need them, don't map them. Depending on your schema/intent, there's certainly no reason to map things you don't need. If you eventually do need them later, add them. Depending on usage, you might want add them for HQL/JPA QL/Criteria queries, or you might want to just do the query in SQL. Eventually, you may need to rework or rethink for caching performance, but that's just the way things go. Just make sure you have a decent test suite.

No big deal. ::shrug::

Generally speaking, adding things later is easy. Deleting isn't bad either. Moving/splitting is the hard one (e.g. splitting a NAME into FIRST and LAST).


OOP is not broken. Relational databases are not broken. There's just an impedance mismatch between the two ways of representing data.

Complex mappings are needed for complex queries that cover multiple tables, with Hibernate performing the necessary joins under the hood.


You might not use them to get the photos, but you will certainly use them in queries. For example:

select user.id, user.name, count(friend.id)
from User user left join user.friends friend
froup by user.id, user.name

to be able to navigate from a user to his friends, you need the friends collection annotated with the OneToMany annotation.

You might make this collection private, and avoid having any accessor to this collection if you want to.

Note that a user, in your example, has probably too many photos and friends to make the collection useful, but it's far from being always the case. I have lots of toMany associations in the application I'm currently working on which have from 0 to 100 elements. And 0 to 10 is pretty frequent.

Also, don't forget that next to your "usual" use-cases, consisting in listing some photos of a user, you will certainly have "unusual" use cases, where you'll have to apply changes in batch to all the photos of a user, or things like that.

0

精彩评论

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