JPA 多对多约束

发布于 2024-10-03 14:53:26 字数 249 浏览 0 评论 0原文

我是 JPA 新手,如果这是一个非常基本的问题,我深表歉意。

我有一个应用程序,用户可以对产品进行投票(范围 0 到 10),但只能投票一次。我很困惑在 JPA 中建立的多对多关系如何允许这样做。

我有一个用户对象、一个投票对象和一个产品对象。

用户可以对产品投票,但只能投票一次。一款产品可以有来自许多用户的多次投票,但每个用户只能投票一次。我如何通过 JPA 注释来设计它?我从数据库设计中清楚地理解了这一点,而不是从 JPA 中。

I am new to JPA, so apologies if this is a very basic problem.

I have an application where a user can vote on a product (range 0 to 10), but can only vote once. I am confused how a manytomany relationship set up in JPA would allow this.

I have a User object and a Vote object and a Product object.

A user can vote on a product, but only once. A product can have many votes, from many users, but only one per user. How would I design this from an JPA annotation? I understand this clearly from a database design, just not from JPA.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

萌能量女王 2024-10-10 14:53:26

由于您使用的是 JPA,它是一个对象关系映射器,因此请按照不涉及 JPA 和数据库的情况来设计它。

我的意思是,以对您尝试捕获的对象和关系有意义的方式构建您的对象模型(java 类),然后担心围绕这些对象正确配置 JPA。

我上次使用 JPA 是在 2.0 推出的时候,所以我不记得规范如何彻底支持使用 java.util.map 实现的字段,但 Map 将是一个很好的方法如果支持的话。

具体来说,在您的 Product 对象中,您可以有一个 Map 类型的字段。

Map<User,Vote> votesOnThisProduct;

但老实说,当您仅从 java 类的角度考虑时,无论 JPA 和数据库思维方式如何,感觉最理性的都是可行的方法。

其他选项是定义其他类,例如

public class ProductVoteRecord
{
    User user;
    Vote vote;
    Product product;
}

然后通过 JPA 注释将 User 和 Product(可能还有投票)设置为复合主键。

但即使是这样的类也显示出受到关系设计毒害的迹象,因为它本质上是一个连接表。

Since you are using JPA, which is an Object-Relational mapper, design it as you would if JPA and Databases were not involved.

What I mean is build your object model (java classes) in the way that would make sense for the objects and relationships you are trying to capture- then worry about configuring JPA correctly around those objects.

The last time I used JPA it was around the time 2.0 was being rolled out, so I don't remember how throughly the specification supports using fields that are implementations of java.util.map, but a Map would be a good way to go if it is supported.

Specifically, in your Product object you could have a field of type Map.

Map<User,Vote> votesOnThisProduct;

But honestly, whatever feels the most rational when you think about it from the perspective of java classes only, ignoring JPA and database mindsets, is the way to go.

Other options would be to define additional classes, such as

public class ProductVoteRecord
{
    User user;
    Vote vote;
    Product product;
}

and then make User and Product (and possibly vote) a compound primary key via JPA annotations.

But even a class like that shows signs of being poisoned by relational design, since it is essentially a joiner table.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文