View Javadoc
1   package model.entity;
2   
3   import lombok.Getter;
4   import lombok.Setter;
5   import org.hibernate.annotations.DynamicUpdate;
6   import org.hibernate.annotations.LazyCollection;
7   import org.hibernate.annotations.LazyCollectionOption;
8   
9   import javax.persistence.*;
10  import java.io.Serializable;
11  import java.time.Instant;
12  import java.util.HashMap;
13  import java.util.List;
14  import java.util.Map;
15  
16  /**
17   * Entità rappresentante un post
18   */
19  @Entity
20  @DynamicUpdate
21  public class Post implements Serializable {
22      public enum Type {TEXT, IMG}
23  
24      @Getter @Setter
25      @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
26      protected Integer id;
27  
28      @Setter @Getter
29      @Column(length = 255, nullable = false)
30      protected String title;
31  
32      @Getter @Setter
33      @Column(columnDefinition = "TEXT", nullable = false)
34      protected String content;
35  
36      @Setter @Getter
37      @Column(nullable = false) @Enumerated(EnumType.STRING)
38      protected Type type;
39  
40      @Getter
41      @Column(nullable = false, updatable = false, insertable = false)
42      protected Instant creationDate; //generato da sql
43  
44      @Getter
45      @Column(name = "votes", nullable = false, insertable = false, updatable = false)
46      protected Integer votesCount;
47  
48      @OneToMany(mappedBy="post")
49      @LazyCollection(LazyCollectionOption.EXTRA)
50      protected List<Comment> comments;
51      public int getCommentCount(){
52          return comments == null ? 0 : comments.size();
53      }
54  
55      @Getter @Setter
56      @ManyToOne(fetch = FetchType.LAZY, optional = false)
57      protected Section section;
58  
59      @Getter @Setter
60      @ManyToOne(fetch = FetchType.LAZY, optional = false)
61      protected User author;
62  
63      @OneToMany(mappedBy="post")
64      @MapKeyJoinColumn(name="user_id", updatable = false, insertable = false)
65      protected Map<User, PostVote> votes = new HashMap<>();
66  
67      /**
68       * Ottieni il voto di un utente al post in questione (o <pre>null</pre> se il voto non è presente)
69       * @param user Riferimento all'utente
70       * @return Un oggetto {@link PostVote}
71       */
72      public PostVote getVote(User user){
73          return votes.get(user);
74      }
75  
76      public Post(){}
77  
78      @Override
79      public boolean equals(Object o) {
80          if (this == o) return true;
81          if (!(o instanceof Post)) return false;
82          Post post = (Post) o;
83          return id != null && id.equals(post.id);
84      }
85  
86      @Override
87      public int hashCode() {
88          return getClass().hashCode();
89      }
90  }