简体   繁体   中英

JPA ManyToMany constraints

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM