开发者

JPA: when to use a ManyToOne relationship vs. value?

I'm a newbie in JPA, and this question is about recommended ways to work with JPA relationships.

I have entities Data and Subject, I can either create a ManyToOne relationship between them, or not. What is a better approach?

Without relationship:

class Data{
 String id;
 String subject;
}

class Subject{
 String id;
 String name;
}

With relationship:

class Data{
 String id;
 @ManyToOne
 Subject subject;
}

class Subject{
 String id;
 String name;
}

Seems like without ManyToOne relationship I have less actions to perform: I shouldn't get Subject entity every time I add a Data entity, I can write simple queries that add/update/delete Data.

On the other hand, ManyToOne validates that Data.subject gets correct values and expla开发者_JAVA技巧ins the relationship between entities, and I get "for free" several queries for Subject and related Data.

What's a better approach? thanks.


the big advantage of jpa/orm is, that you can directly access to objects. So you should choose the example with @ManyToOne-Anotation.

If you worry about the actions performed against the database, "lazy loading" will be your friend.

Best regards,

Chris

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜