简体   繁体   中英

Hibernate: entity relationships and extra table

I'm creating rating system for simple web application that allows users to post text, similiar to twitter's wall. I've got two entities:

First one:

@Entity
@Table(name = "user")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @Column(unique = true)
    private String login;

    private String hashPassword;
    private String name;
    private String surname;

    @Column(unique = true)
    private String email;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "connectedUser", fetch = FetchType.EAGER)
    private List<Post> userPosts = new ArrayList<>();

Second one:

@Entity
@Table(name = "post")
public class Post {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    private String text;

    @NotNull
    private LocalDateTime postDate;

    @ManyToOne(optional = false)
    @JoinColumn(name = "user_id")
    private User connectedUser;

And I'm trying to figure out, where/how to add something responsible for rating. Every single post can be rated once per user (Plus or minus) and total sum of rate should be displayed nearby. It seems simple, I need separate table in database with user_id, post_id, and rate, but how could I do that in Hibernate (Hibernate creates database by itself)? Is there any simple solution for this?

If you need additional table - you need additional Entity.

For storing the user actions related to post:

@Entity
@Table(name = "user_post_rate")
public class UserPostRate {

    @OneToMany
    private Post post;
    @OneToOne
    private User user;
    private boolean upvote;
    // ...
}

It could be just boolean value if you have two fixed actions related to the post . You can replace it with some integer values, let's say, for example if privileged user can upvode it for + n , or user can upvote it again after some time and etc.

However you still need sum of rated values to be stored somewhere (not to calculate it time after time).

The overall post score is not a good place to be stored in the same table when user-post related actions are stored, because you will keep many unnecessary duplicates here (until you'll need to keep track of post score history). You can store it in Post entity, because the score of the post is part of its state:

@Entity
@Table(name = "post")
public class Post {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    // skipped

    private long score;
}

Every time a user will rate the post, update for the post entity score should be triggered.

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