steeve
steeve

Reputation: 47

In what structure should I keep pair values from both hibernate entities

I have two entities User and Discount. User can have many discounts (bonuses, extra points whatever) and a discount can be applied to many users.

With these relational mappings I get three tables: User, Discount and User_Discount.

I create public Discount (for all users), set isActivated = true and save the discount object in every user (not sure if it's good for performance).

My problem is, when I want to deactivate discount for one user -> I get user by id, get discount object and set field isActivated to false and after that operation every user has this discount field set to false. So it's one shared object for every user. I want activate/deactivate separately for users. How to resolve that? In what structure should I keep this flag activated/deactivated?

User_Discount table I actually need to get info if a specific discount is assigned to any user and if I can delete it. Maybe I don't need this mapping?

@Data
@Entity
public class Discount {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;
    private boolean isActivated;
    private BigDecimal value;
    private String discount_group;

    @ManyToMany
    @JoinTable(name = "user_discount", joinColumns = @JoinColumn(name = "discount_id"),
            inverseJoinColumns = @JoinColumn(name = "user_id"))
    @JsonIgnore
    private Set<User> users = new HashSet<>();
}

@Data
@Entity
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long user_id;
    private String firstName;
    private String lastName;

    @ManyToMany(mappedBy = "users")
    private Set<Discount> discounts = new HashSet<>();

}

Upvotes: 1

Views: 55

Answers (1)

Flmzor
Flmzor

Reputation: 26

You need to create an entity class for your User_Discount table and add the additional fields you want to it. Get a User_Discount entity by user and change the flag in it. check out this article.

Upvotes: 1

Related Questions