1 | |
package models; |
2 | |
|
3 | |
import java.util.*; |
4 | |
import javax.persistence.*; |
5 | |
|
6 | |
import play.db.jpa.*; |
7 | |
import play.data.validation.*; |
8 | |
|
9 | |
@Entity |
10 | |
public class Post extends Model { |
11 | |
|
12 | |
@Required |
13 | |
public String title; |
14 | |
|
15 | |
@Required |
16 | |
public Date postedAt; |
17 | |
|
18 | |
@Lob |
19 | |
@Required |
20 | |
@MaxSize(10000) |
21 | |
public String content; |
22 | |
|
23 | |
@Required |
24 | |
@ManyToOne |
25 | |
public User author; |
26 | |
|
27 | |
@OneToMany(mappedBy = "post", cascade = CascadeType.ALL) |
28 | |
public List<Comment> comments; |
29 | |
|
30 | |
@ManyToMany(cascade = CascadeType.PERSIST) |
31 | |
public Set<Tag> tags; |
32 | |
|
33 | 15 | public Post(User author, String title, String content) { |
34 | 15 | this.comments = new ArrayList<Comment>(); |
35 | 15 | this.tags = new TreeSet(); |
36 | 15 | this.author = author; |
37 | 15 | this.title = title; |
38 | 15 | this.content = content; |
39 | 15 | this.postedAt = new Date(); |
40 | 15 | } |
41 | |
|
42 | |
public Post addComment(String author, String content) { |
43 | 9 | Comment newComment = new Comment(this, author, content); |
44 | 9 | this.comments.add(newComment); |
45 | 9 | this.save(); |
46 | 9 | return this; |
47 | |
} |
48 | |
|
49 | |
public Post previous() { |
50 | 0 | return Post.find("postedAt < ? order by postedAt desc", postedAt).first(); |
51 | |
} |
52 | |
|
53 | |
public Post next() { |
54 | 0 | return Post.find("postedAt > ? order by postedAt asc", postedAt).first(); |
55 | |
} |
56 | |
|
57 | |
public Post tagItWith(String name) { |
58 | 12 | tags.add(Tag.findOrCreateByName(name)); |
59 | 12 | return this; |
60 | |
} |
61 | |
|
62 | |
public static List<Post> findTaggedWith(String tag) { |
63 | 24 | return Post.find( |
64 | 12 | "select distinct p from Post p join p.tags as t where t.name = ?", |
65 | 12 | tag |
66 | 12 | ).fetch(); |
67 | |
} |
68 | |
|
69 | |
public static List<Post> findTaggedWith(String... tags) { |
70 | 24 | return Post.find( |
71 | 12 | "select distinct p from Post p join p.tags as t where t.name in (:tags) group by p.id, p.author, p.title, p.content,p.postedAt having count(t.id) = :size" |
72 | 12 | ).bind("tags", tags).bind("size", tags.length).fetch(); |
73 | |
} |
74 | |
|
75 | |
public String toString() { |
76 | 51 | return title; |
77 | |
} |
78 | |
|
79 | |
} |