1
2
3
4
5 package org.greatage.domain;
6
7 import org.greatage.util.DescriptionBuilder;
8
9 import java.io.Serializable;
10 import java.util.ArrayList;
11 import java.util.Collection;
12 import java.util.List;
13
14
15
16
17
18 public class EntityQuery<PK extends Serializable, E extends Entity<PK>, Q extends EntityQuery<PK, E, Q>>
19 implements EntityFilter<PK, E> {
20
21 private final Class<E> entityClass;
22 private EntityRepository repository;
23 private String queryString;
24 private List<PK> includeKeys;
25 private List<PK> excludeKeys;
26
27 public EntityQuery(final Class<E> entityClass) {
28 this.entityClass = entityClass;
29 }
30
31 public EntityQuery(final EntityRepository repository, final Class<E> entityClass) {
32 this.repository = repository;
33 this.entityClass = entityClass;
34 }
35
36
37
38
39
40
41 public Class<E> getEntityClass() {
42 return entityClass;
43 }
44
45
46
47
48
49
50 public String getQueryString() {
51 return queryString;
52 }
53
54
55
56
57
58
59 public Collection<PK> getIncludeKeys() {
60 return includeKeys;
61 }
62
63
64
65
66
67
68 public Collection<PK> getExcludeKeys() {
69 return excludeKeys;
70 }
71
72
73
74
75
76
77
78 public Q setQueryString(final String queryString) {
79 this.queryString = queryString;
80 return query();
81 }
82
83
84
85
86
87
88
89 public Q includeKeys(final Collection<PK> keys) {
90 if (includeKeys == null) {
91 includeKeys = new ArrayList<PK>();
92 }
93 includeKeys.addAll(keys);
94 return query();
95 }
96
97
98
99
100
101
102
103 public Q excludeKeys(final Collection<PK> keys) {
104 if (excludeKeys == null) {
105 excludeKeys = new ArrayList<PK>();
106 }
107 excludeKeys.addAll(keys);
108 return query();
109 }
110
111 public Q assign(final EntityRepository repository) {
112 this.repository = repository;
113 return query();
114 }
115
116
117
118
119
120
121 public int count() {
122 return repository().count(this);
123 }
124
125
126
127
128
129
130
131 public List<E> list(final Pagination pagination) {
132 return repository().find(this, pagination);
133 }
134
135
136
137
138
139
140 public List<E> list() {
141 return repository().find(this, Pagination.ALL);
142 }
143
144
145
146
147
148
149 public E unique() {
150 return repository().findUnique(this);
151 }
152
153
154
155
156
157
158
159 protected EntityRepository repository() {
160 if (repository == null) {
161 throw new IllegalStateException("This query is not assigned to repository.");
162 }
163 return repository;
164 }
165
166
167
168
169
170
171 @SuppressWarnings({"unchecked"})
172 protected Q query() {
173 return (Q) this;
174 }
175
176 @Override
177 public String toString() {
178 final DescriptionBuilder builder = new DescriptionBuilder(getClass());
179 builder.append("class", entityClass);
180 builder.append("queryString", queryString);
181 return builder.toString();
182 }
183 }