开发者

JPA : best practices with unidirectional OneToMany

I have several little questions about best practices with JPA (via hibernate).

My first question is about the complexity of one domain model. I've got a model Account which represents an... account ;) An account have a lot of relations with other objects. A lot of them need to be known by the Account object but some of them need to be known only for the other part.

For example, I've got a Message model which represents a message that is sent to an Account. I don't really want to override my Account model with a new relation because it has already lot of relations, so I decide to make the relation between Account and Model unidirectional.

So, I've mapped the relation with a ManyToOne relation only in the Message class and not in Account.

Do you think it is a good practice just to 开发者_高级运维avoid too much relations in a model class (Account in my case) ? Or do you think I must map ALL relations to an Account in my Account class. So, what's the best practice, unidirectional or bidirectional relations ?

My second question comes from the unidirectional case. When I remove an account, due to unidirectional relation, all messages refering this account now failed to load because the parent Account is missing.

What's the best practice to maintain a non corrupted database ? - delete all relations when the account is deleted (can be very dangerous in term of performance) - make a job which delete progressively all relations and deactivate the account during this process

Thank you for all suggestions ;)


You may use unidirectional relationships without problem if you don't need to navigate from an account to its messages (in code or in queries).

whatever the solution you choose, you should define a foreign key constraint between the message and its account. This way, deleting an account without first deleting its messages will throw an exception. This is how you guarantee that the data coherence is not corrupted. If you want to be able to delete an account without deleting its messages, then you should first detach the account from its messages, by setting their account ManyToOne field to null. Of course, the relationship must be marked optional, and the forein key column must be nullable.

Note, though, that having a relationship from the account to its messages (even if it's not accessible from the rest of the code) would allow you to

  • use this relationship inside queries
  • set a cascade delete on the relationship, so that all messages are automatically deleted before an account is deleted.
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜