001package model.entity; 002 003import lombok.Getter; 004import lombok.Setter; 005import org.hibernate.annotations.DynamicUpdate; 006import org.hibernate.annotations.LazyCollection; 007import org.hibernate.annotations.LazyCollectionOption; 008 009import javax.persistence.*; 010import java.io.Serializable; 011import java.time.Instant; 012import java.util.HashMap; 013import java.util.List; 014import java.util.Map; 015 016/** 017 * Entità rappresentante un post 018 */ 019@Entity 020@DynamicUpdate 021public class Post implements Serializable { 022 public enum Type {TEXT, IMG} 023 024 @Getter @Setter 025 @Id @GeneratedValue(strategy = GenerationType.IDENTITY) 026 protected Integer id; 027 028 @Setter @Getter 029 @Column(length = 255, nullable = false) 030 protected String title; 031 032 @Getter @Setter 033 @Column(columnDefinition = "TEXT", nullable = false) 034 protected String content; 035 036 @Setter @Getter 037 @Column(nullable = false) @Enumerated(EnumType.STRING) 038 protected Type type; 039 040 @Getter 041 @Column(nullable = false, updatable = false, insertable = false) 042 protected Instant creationDate; //generato da sql 043 044 @Getter 045 @Column(name = "votes", nullable = false, insertable = false, updatable = false) 046 protected Integer votesCount; 047 048 @OneToMany(mappedBy="post") 049 @LazyCollection(LazyCollectionOption.EXTRA) 050 protected List<Comment> comments; 051 public int getCommentCount(){ 052 return comments == null ? 0 : comments.size(); 053 } 054 055 @Getter @Setter 056 @ManyToOne(fetch = FetchType.LAZY, optional = false) 057 protected Section section; 058 059 @Getter @Setter 060 @ManyToOne(fetch = FetchType.LAZY, optional = false) 061 protected User author; 062 063 @OneToMany(mappedBy="post") 064 @MapKeyJoinColumn(name="user_id", updatable = false, insertable = false) 065 protected Map<User, PostVote> votes = new HashMap<>(); 066 067 /** 068 * Ottieni il voto di un utente al post in questione (o <pre>null</pre> se il voto non è presente) 069 * @param user Riferimento all'utente 070 * @return Un oggetto {@link PostVote} 071 */ 072 public PostVote getVote(User user){ 073 return votes.get(user); 074 } 075 076 public Post(){} 077 078 @Override 079 public boolean equals(Object o) { 080 if (this == o) return true; 081 if (!(o instanceof Post)) return false; 082 Post post = (Post) o; 083 return id != null && id.equals(post.id); 084 } 085 086 @Override 087 public int hashCode() { 088 return getClass().hashCode(); 089 } 090}