├── .gitignore
├── .travis.yml
├── LICENSE
├── README.md
├── pom.xml
└── src
├── img
└── property-selector.png
├── main
└── java
│ └── com
│ └── jaxio
│ └── jpa
│ └── querybyexample
│ ├── ByExampleUtil.java
│ ├── ByFullTextUtil.java
│ ├── ByNamedQueryUtil.java
│ ├── ByPatternUtil.java
│ ├── ByPropertySelectorUtil.java
│ ├── ByRangeUtil.java
│ ├── DefaultLuceneQueryBuilder.java
│ ├── EntityGraphLoader.java
│ ├── GenericRepository.java
│ ├── HibernateSearchUtil.java
│ ├── Identifiable.java
│ ├── JpaUniqueUtil.java
│ ├── JpaUtil.java
│ ├── LabelizedEnum.java
│ ├── LuceneQueryBuilder.java
│ ├── MetamodelUtil.java
│ ├── OrderBy.java
│ ├── OrderByDirection.java
│ ├── OrderByUtil.java
│ ├── PathHolder.java
│ ├── PropertySelector.java
│ ├── Range.java
│ ├── RepositoryLocator.java
│ ├── SearchMode.java
│ ├── SearchParameters.java
│ └── TermSelector.java
└── test
├── java
└── demo
│ ├── Account.java
│ ├── AccountQueryByExampleTest.java
│ ├── AccountRepository.java
│ ├── Account_.java
│ ├── Address.java
│ ├── Address_.java
│ ├── IdentifiableHashBuilder.java
│ └── JpaConfiguration.java
└── resources
├── 01-create.sql
├── META-INF
└── persistence.xml
├── applicationContext.xml
└── hibernate.properties
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | target/
3 | .idea/
4 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: java
2 | jdk:
3 | - oraclejdk8
4 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ## JPA Query by Example framework
2 |
3 | [](https://travis-ci.org/jaxio/jpa-query-by-example)
4 |
5 | Query By Example for JPA is originally inspired from [Hibernate Example criterion](https://docs.jboss.org/hibernate/orm/3.6/reference/en-US/html/querycriteria.html#querycriteria-examples
6 | ). But since Hibernate's Example is not part of JPA 2, we have created our own API, using JPA 2 only.
7 |
8 |
9 | ## How To Use QBE
10 |
11 | We do not cover here QBE implementation details, instead we explain how to use the Query By Example API.
12 |
13 | JPA Query by Example is available on Maven central repository:
14 |
15 | ```xml
16 |
17 | com.jaxio
18 | jpa-querybyexample
19 | 1.0.1
20 |
21 | ```
22 |
23 | #### Resources
24 |
25 | * Take a look directly at the [QBE junit tests](https://github.com/jaxio/jpa-query-by-example/blob/master/src/test/java/demo), they are almost self-explanatory.
26 | * Use Celerio to generate an advanced CRUD application that leverages this QBE API. See [Celerio](http://www.jaxio.com/documentation/celerio/installation.html)
27 | * [Watch a demo of an application generated by Celerio](https://www.facebook.com/video/video.php?v=524162864265905¬if_t=video_processed)
28 |
29 |
30 | ### Simple Query By Example
31 |
32 | In its simplest form, Query By Example allows you to construct a query from a given entity instance.
33 |
34 | Let's assume we have an [Account entity](https://github.com/jaxio/jpa-query-by-example/blob/master/src/test/java/demo/Account.java)
35 | having a `lastName` property and that we want to query all accounts whose last name matches 'Jagger'.
36 |
37 | Using QBE, constructing the query is as simple as setting the lastName...:
38 |
39 | ```java
40 | Account example = new Account();
41 | example.setLastName("Jagger");
42 | List result = accountRepository.find(example);
43 | ```
44 |
45 | At the SQL level, the resulting query looks like this:
46 |
47 | ```sql
48 | select
49 | -- skip other fields for clarity
50 | account0_.LAST_NAME as LAST9_3_,
51 | from
52 | Account account0_
53 | where
54 | account0_.LAST_NAME=?
55 | ```
56 |
57 | The [AccountRepository](https://github.com/jaxio/jpa-query-by-example/blob/master/src/test/java/demo/AccountRepository.java)
58 | extends a [GenericRepository](https://github.com/jaxio/jpa-query-by-example/blob/master/src/main/java/com/jaxio/jpa/querybyexample/GenericRepository.java)
59 |
60 | #### Case sensitivity, order by
61 |
62 | The first query above involves a String. Let's change it to make it case insensitive.
63 |
64 | Our `Account` entity does not carry case sensitivity meta information. For this reason, we require some extra parameters
65 | for case sensitivity, but also ordering, etc.
66 | The number of parameters can grow quickly, so we have grouped them in the
67 | [SearchParameters](https://github.com/jaxio/jpa-query-by-example/blob/master/src/main/java/com/jaxio/jpa/querybyexample/SearchParameters.java) class
68 | which can be passed as a parameter to the accountRepository's methods.
69 |
70 | Let's make the first query above `case insensitive` and let's add an `ORDER BY`.
71 |
72 | ```java
73 | Account example = new Account();
74 | example.setLastName("Jagger");
75 | SearchParameters sp = new SearchParameters().caseSensitive().orderBy(OrderByDirection.ASC, Account_.lastName);
76 | List result = accountRepository.find(example, sp);
77 | ```
78 |
79 | Note the usage of the
80 | [Account_](https://github.com/jaxio/jpa-query-by-example/blob/master/src/test/java/demo/Account_.java)*
81 | static metamodel, which helps you to keep your query related Java code strongly typed.
82 |
83 | At the SQL level, the resulting FROM clause now looks like this:
84 |
85 | ```sql
86 | from
87 | ACCOUNT account0_
88 | where
89 | lower(account0_.LAST_NAME)=?
90 | order by
91 | account0_.LAST_NAME asc
92 | ```
93 |
94 | #### Pagination
95 |
96 | In most web application we need to paginate the query results in order to save resources. In the query below, we retrieve only
97 | the 3rd page (we assume a page lists 25 rows). The first result is the 50th element and we retrieve at most 25 elements.
98 |
99 | ```java
100 | Account example = new Account();
101 | example.setLastName("Jagger");
102 | SearchParameters sp = new SearchParameters().orderBy(OrderByDirection.ASC, Account_.lastName) //
103 | .first(50).maxResults(25);
104 | List result = accountRepository.find(example, sp);
105 | ```
106 |
107 | At the SQL level, the resulting FROM clause now looks like this (we use H2 database):
108 |
109 | ```sql
110 | from
111 | ACCOUNT account0_
112 | where
113 | account0_.LAST_NAME=?
114 | order by
115 | account0_.LAST_NAME asc limit ? offset ?
116 | ```
117 |
118 | #### LIKE and String
119 |
120 | For strings, you can globally control whether a `LIKE` should be used and where the `%` wildcard should be placed. For example, adding :
121 |
122 | ```java
123 | example.setLastName("Jag");
124 | SearchParameters sp = new SearchParameters().startingLike();
125 | ```
126 |
127 | to our example above would result in
128 |
129 | ```sql
130 | account0_.LAST_NAME LIKE 'Jag%'
131 | ```
132 |
133 | #### Multiple criteria
134 |
135 | Until now, we have worked only with one property, lastName, but we can set other properties, for example:
136 |
137 | ```java
138 | Account example = new Account();
139 | example.setLastName("Jag");
140 | example.setBirthDate(new Date());
141 | SearchParameters sp = new SearchParameters().orderBy(OrderByDirection.ASC, Account_.lastName).startingLike();
142 | List result = accountRepository.find(example, sp);
143 | ```
144 |
145 | By default, the FROM clause uses a `AND` predicate.
146 |
147 | ```sql
148 | from
149 | ACCOUNT account0_
150 | where
151 | account0_.BIRTH_DATE=?
152 | and (
153 | account0_.LAST_NAME like ?
154 | )
155 | order by
156 | account0_.LAST_NAME asc
157 | ```
158 |
159 | To use instead `OR`, use the `.orMode()`, as follow:
160 |
161 | ```java
162 | SearchParameters sp = new SearchParameters().orMode().orderBy(OrderByDirection.ASC, Account_.lastName).startingLike();
163 | ```
164 |
165 | And this time we get:
166 |
167 | ```sql
168 | where
169 | account0_.LAST_NAME like ?
170 | or account0_.BIRTH_DATE=?
171 | order by
172 | account0_.LAST_NAME asc
173 | ```
174 |
175 | #### Is that all ?
176 |
177 | Not really, we have just scratched the surface. For the moment, we have covered only rather simple queries.
178 | While simplicity is key, it is often not sufficient. What about date or number range queries ? What about associated entities ? etc.
179 |
180 | ### Beyond Query By Example
181 |
182 | #### Mixing Query by Example and Range Query.
183 |
184 | Now, let's imagine that you also want to restrict the query above to all accounts having their date of birth between 1940 and 1945 included.
185 | Of course, the entity does not have the appropriate property (from & to).
186 | For this reason, we introduce an additional
187 | [Range](https://github.com/jaxio/jpa-query-by-example/blob/master/src/main/java/com/jaxio/jpa/querybyexample/Range.java)
188 | parameter.
189 |
190 | Here is an example:
191 |
192 | ```java
193 | Account example = new Account();
194 | example.setLastName("Jagger");
195 |
196 | Calendar from = Calendar.getInstance();
197 | from.set(1940, 0, 1);
198 |
199 | Calendar to = Calendar.getInstance();
200 | to.set(1945, 11, 31);
201 |
202 | Range birthDateRange = Range.newRange(Account_.birthDate);
203 | birthDateRange.from(from.getTime()).to(to.getTime());
204 |
205 | SearchParameters sp = new SearchParameters().range(birthDateRange);
206 | List result = accountRepository.find(example, sp);
207 | ```
208 |
209 | Note that you can add ranges of any type: Integer, Long, LocalDate (joda time), BigDecimal, etc...
210 |
211 | This codes leads in fine to following `FROM` clause:
212 |
213 | ```sql
214 | from
215 | ACCOUNT account0_
216 | where
217 | (
218 | account0_.BIRTH_DATE between ? and ?
219 | )
220 | and account0_.LAST_NAME=?
221 | ```
222 |
223 | Here is a variation of the same example (depends on need, taste and color :-):
224 |
225 | ```java
226 | DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
227 | Date from = dateFormat.parse("1920-12-01");
228 | Date to = dateFormat.parse("1974-12-01");
229 |
230 | SearchParameters sp = new SearchParameters().range(from, to, Account_.birthDate);
231 | List accountList = accountRepository.find(sp);
232 | ```
233 |
234 | #### Query all string properties in a OR clause
235 |
236 | To find all entities having at least one of their String property matching a given value, use the `searchPattern` method.
237 |
238 | Here is an example:
239 |
240 | ```java
241 | SearchParameters sp = new SearchParameters().searchMode(SearchMode.STARTING_LIKE).searchPattern("Jag");
242 | List result = accountRepository.find(sp);
243 | ```
244 |
245 | The FROM clause now includes all string columns:
246 |
247 | ```sql
248 | from
249 | ACCOUNT account0_
250 | where
251 | or account0_.LAST_NAME like ?
252 | or account0_.USERNAME like ?
253 | ```
254 |
255 | #### Property Selector
256 |
257 | In order to construct a `OR` clause for a given property we use the `PropertySelector` class.
258 |
259 | Here is an example:
260 |
261 | ```java
262 | PropertySelector lastNameSelector = PropertySelector.newPropertySelector(Account_.lastName);
263 | lastNameSelector.setSelected(Arrays.asList("Jagger", "Richards", "Jones", "Watts", "taylor", "Wyman", "Wood"));
264 |
265 | SearchParameters sp = new SearchParameters().property(lastNameSelector);
266 |
267 | List result = accountRepository.find(sp);
268 | ```
269 |
270 | Here is the corresponding FROM clause:
271 |
272 | ```sql
273 | from
274 | ACCOUNT account0_
275 | where
276 | account0_.LAST_NAME='Jagger'
277 | or account0_.LAST_NAME='Richards'
278 | or account0_.LAST_NAME='Jones'
279 | or account0_.LAST_NAME='Watts'
280 | or account0_.LAST_NAME='Taylor'
281 | or account0_.LAST_NAME='Wyman'
282 | or account0_.LAST_NAME='Wood'
283 | ```
284 |
285 | Note that if you use JSF2 with PrimeFaces, you can directly pass a `PropertySelector` to a multiple autoComplete component's value property.
286 | This way, the autoComplete component fills the PropertySelector. Here is how:
287 |
288 | ```xml
289 |
290 | ```
291 |
292 | Here is a snapshot:
293 |
294 | 
295 |
296 | PrimeFaces uses the `setSelected(List selection)` method to fill the lastNameSelector.
297 |
298 | #### Mix it all
299 |
300 | Remember, you can mix all the example we have seen so far.
301 | You can have in a single query having multiple ranges, multiple property selector, multiple properties set on the example entity, etc.
302 |
303 | This gives you great power ;-)
304 |
305 | #### Query By Example on association
306 |
307 | The `Account` entity has a `@ManyToOne` association with the `Address` entity.
308 |
309 | Here is how we can retrieve all accounts pointing to an Address having its `city` property set to "Paris":
310 |
311 | ```java
312 | Account example = new Account();
313 | example.setHomeAddress(new Address());
314 | example.getHomeAddress().setCity("Paris");
315 | List result = accountRepository.find(example);
316 | Assert.assertThat(result.size(), is(2));
317 | ```
318 |
319 | The FROM clause uses a JOIN:
320 |
321 | ```sql
322 | from
323 | ACCOUNT account0_ cross
324 | join
325 | ADDRESS address1_
326 | where
327 | account0_.ADDRESS_ID=address1_.ID
328 | and address1_.CITY='Paris'
329 | ```
330 |
331 | Enjoy!
332 |
333 |
334 | ## License
335 |
336 | The JPA Query By Example Framework is released under version 2.0 of the [Apache License][].
337 |
338 | [Apache License]: http://www.apache.org/licenses/LICENSE-2.0
339 |
340 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 4.0.0
4 |
5 |
6 | 3.1.1
7 |
8 |
9 | com.jaxio
10 | jpa-querybyexample
11 | jar
12 | 1.0.2-SNAPSHOT
13 |
14 | JPA Query by Example
15 | https://github.com/jaxio/jpa-query-by-example
16 | This API allows you to construct Query By Example using the JPA 2 Criteria API.
17 |
18 |
19 |
20 | nromanetti
21 | Nicolas Romanetti
22 | romanetti@gmail.com
23 |
24 |
25 | framiere
26 | Florent Ramiere
27 | florent@ramiere.com
28 |
29 |
30 | jeanlouisboudart
31 | Jean-Louis Boudart
32 | jeanlouis.boudart@gmail.com
33 |
34 |
35 |
36 |
37 | JAXIO
38 | http://www.jaxio.com
39 |
40 |
41 |
42 |
43 | Apache License 2.0
44 | http://www.apache.org/licenses/LICENSE-2.0.html
45 | repo
46 |
47 |
48 |
49 |
50 | scm:git:git://github.com/jaxio/jpa-query-by-example.git
51 | scm:git:git@github.com:jaxio/jpa-query-by-example.git
52 | http://github.com/jaxio/jpa-query-by-example/
53 | HEAD
54 |
55 |
56 |
57 | github
58 | http://github.com/jaxio/jpa-query-by-example/issues#issue/
59 |
60 |
61 |
62 |
63 |
64 |
65 | UTF-8
66 | UTF-8
67 |
68 |
69 |
70 | 5.0.2.Final
71 | 4.2.2.RELEASE
72 | 4.0.2.RELEASE
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 | javax.inject
81 | javax.inject
82 | 1
83 |
84 |
85 |
86 |
87 |
88 |
89 | org.hibernate.javax.persistence
90 | hibernate-jpa-2.1-api
91 | 1.0.0.Final
92 |
93 |
94 | org.hibernate
95 | hibernate-core
96 | ${hibernate.version}
97 |
98 |
99 | org.hibernate
100 | hibernate-entitymanager
101 | ${hibernate.version}
102 |
103 |
104 | org.hibernate
105 | hibernate-java8
106 | ${hibernate.version}
107 |
108 |
109 | cglib
110 | cglib
111 | 3.1
112 | runtime
113 |
114 |
115 |
116 |
117 |
118 | org.hibernate
119 | hibernate-search
120 | 5.5.0.Final
121 |
122 |
123 | lucene-kuromoji
124 | org.apache.lucene
125 |
126 |
127 |
128 |
129 | org.apache.solr
130 | solr-common
131 | 1.3.0
132 |
133 |
134 | org.apache.solr
135 | solr-core
136 | 5.3.1
137 |
138 |
139 | org.apache.tika
140 | tika-parsers
141 | 1.11
142 |
143 |
144 | commons-logging
145 | commons-logging
146 |
147 |
148 |
149 |
150 | org.codehaus.jackson
151 | jackson-mapper-asl
152 | 1.9.13
153 |
154 |
155 |
156 |
157 |
158 | org.slf4j
159 | slf4j-api
160 | 1.7.12
161 |
162 |
163 | org.slf4j
164 | log4j-over-slf4j
165 | 1.7.12
166 |
167 |
168 | org.slf4j
169 | jcl-over-slf4j
170 | 1.7.12
171 |
172 |
173 | ch.qos.logback
174 | logback-classic
175 | 1.1.3
176 |
177 |
178 |
179 |
180 |
181 | com.google.guava
182 | guava
183 | 18.0
184 |
185 |
186 |
187 |
188 |
189 |
190 |
191 |
192 |
193 |
194 |
195 |
196 | commons-beanutils
197 | commons-beanutils
198 | 1.9.2
199 |
200 |
201 | commons-logging
202 | commons-logging
203 |
204 |
205 |
206 |
207 |
208 |
209 |
210 | org.springframework
211 | spring-context
212 | ${spring.version}
213 |
214 |
215 | commons-logging
216 | commons-logging
217 |
218 |
219 |
220 |
221 | org.springframework
222 | spring-expression
223 | ${spring.version}
224 |
225 |
226 | org.springframework
227 | spring-jdbc
228 | ${spring.version}
229 |
230 |
231 | org.springframework
232 | spring-orm
233 | ${spring.version}
234 |
235 |
236 | org.springframework
237 | spring-aspects
238 | ${spring.version}
239 |
240 |
241 | org.springframework
242 | spring-aop
243 | ${spring.version}
244 |
245 |
246 | org.aspectj
247 | aspectjrt
248 | 1.8.7
249 |
250 |
251 | org.aspectj
252 | aspectjweaver
253 | 1.8.7
254 |
255 |
256 |
257 | com.h2database
258 | h2
259 | 1.4.190
260 | test
261 |
262 |
263 | junit
264 | junit
265 | 4.12
266 | test
267 |
268 |
269 | org.springframework
270 | spring-test
271 | 4.2.2.RELEASE
272 | test
273 |
274 |
275 |
276 |
277 |
278 |
279 | org.apache.maven.plugins
280 | maven-deploy-plugin
281 | 2.8.1
282 |
283 |
284 | org.apache.maven.plugins
285 | maven-compiler-plugin
286 | 2.0.2
287 |
288 | 1.8
289 | 1.8
290 | 1.8
291 | UTF-8
292 |
293 |
294 |
295 |
296 | org.apache.maven.plugins
297 | maven-release-plugin
298 | 2.5.2
299 |
300 | release
301 | true
302 |
303 |
304 |
305 |
306 |
307 |
308 |
309 | sonatype-nexus-snapshots
310 | Sonatype Nexus Snapshots
311 | http://oss.sonatype.org/content/repositories/snapshots
312 |
313 |
314 | sonatype-nexus-staging
315 | Nexus Release Repository
316 | http://oss.sonatype.org/service/local/staging/deploy/maven2/
317 |
318 |
319 |
320 |
321 |
322 | release
323 |
324 |
325 |
326 | maven-gpg-plugin
327 | 1.6
328 |
329 |
330 | sign-artifacts
331 | verify
332 |
333 | sign
334 |
335 |
336 |
337 |
338 |
339 |
340 |
341 |
342 |
343 |
344 |
--------------------------------------------------------------------------------
/src/img/property-selector.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jaxio/jpa-query-by-example/7ee8503a5823ae5504d31fbdac24e0c7bd608828/src/img/property-selector.png
--------------------------------------------------------------------------------
/src/main/java/com/jaxio/jpa/querybyexample/ByExampleUtil.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2015 JAXIO http://www.jaxio.com
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.jaxio.jpa.querybyexample;
17 |
18 | import org.slf4j.Logger;
19 | import org.slf4j.LoggerFactory;
20 |
21 | import javax.inject.Inject;
22 | import javax.inject.Named;
23 | import javax.inject.Singleton;
24 | import javax.persistence.EntityManager;
25 | import javax.persistence.PersistenceContext;
26 | import javax.persistence.criteria.*;
27 | import javax.persistence.metamodel.ManagedType;
28 | import javax.persistence.metamodel.PluralAttribute;
29 | import javax.persistence.metamodel.SingularAttribute;
30 | import java.util.List;
31 |
32 | import static com.google.common.collect.Lists.newArrayList;
33 | import static java.util.Collections.emptyList;
34 | import static javax.persistence.metamodel.Attribute.PersistentAttributeType.*;
35 | import static org.apache.commons.lang.StringUtils.isNotEmpty;
36 |
37 | /**
38 | * Helper to create predicate by example. It processes associated entities (1 level deep).
39 | */
40 | @Named
41 | @Singleton
42 | public class ByExampleUtil {
43 | private static final Logger log = LoggerFactory.getLogger(ByExampleUtil.class);
44 |
45 | @Inject
46 | private JpaUtil jpaUtil;
47 | @PersistenceContext
48 | private EntityManager em;
49 |
50 | public > Predicate byExampleOnEntity(Root rootPath, T entityValue, CriteriaBuilder builder, SearchParameters sp) {
51 | if (entityValue == null) {
52 | return null;
53 | }
54 |
55 | Class type = rootPath.getModel().getBindableJavaType();
56 | ManagedType mt = em.getMetamodel().entity(type);
57 |
58 | List predicates = newArrayList();
59 | predicates.addAll(byExample(mt, rootPath, entityValue, sp, builder));
60 | predicates.addAll(byExampleOnCompositePk(rootPath, entityValue, sp, builder));
61 | predicates.addAll(byExampleOnXToOne(mt, rootPath, entityValue, sp, builder)); // 1 level deep only
62 | predicates.addAll(byExampleOnXToMany(mt, rootPath, entityValue, sp, builder));
63 | return jpaUtil.concatPredicate(sp, builder, predicates);
64 | }
65 |
66 | protected > List byExampleOnCompositePk(Root root, T entity, SearchParameters sp, CriteriaBuilder builder) {
67 | String compositePropertyName = jpaUtil.compositePkPropertyName(entity);
68 | if (compositePropertyName == null) {
69 | return emptyList();
70 | } else {
71 | return newArrayList(byExampleOnEmbeddable(root.get(compositePropertyName), entity.getId(), sp, builder));
72 | }
73 | }
74 |
75 | public Predicate byExampleOnEmbeddable(Path embeddablePath, E embeddableValue, SearchParameters sp, CriteriaBuilder builder) {
76 | if (embeddableValue == null) {
77 | return null;
78 | }
79 |
80 | Class type = embeddablePath.getModel().getBindableJavaType();
81 | ManagedType mt = em.getMetamodel().embeddable(type); // note: calling .managedType() does not work
82 |
83 | return jpaUtil.andPredicate(builder, byExample(mt, embeddablePath, embeddableValue, sp, builder));
84 | }
85 |
86 | /*
87 | * Add a predicate for each simple property whose value is not null.
88 | */
89 | public List byExample(ManagedType mt, Path mtPath, T mtValue, SearchParameters sp, CriteriaBuilder builder) {
90 | List predicates = newArrayList();
91 | for (SingularAttribute super T, ?> attr : mt.getSingularAttributes()) {
92 | if (attr.getPersistentAttributeType() == MANY_TO_ONE //
93 | || attr.getPersistentAttributeType() == ONE_TO_ONE //
94 | || attr.getPersistentAttributeType() == EMBEDDED) {
95 | continue;
96 | }
97 |
98 | Object attrValue = jpaUtil.getValue(mtValue, attr);
99 | if (attrValue != null) {
100 | if (attr.getJavaType() == String.class) {
101 | if (isNotEmpty((String) attrValue)) {
102 | predicates.add(jpaUtil.stringPredicate(mtPath.get(jpaUtil.stringAttribute(mt, attr)), attrValue, sp, builder));
103 | }
104 | } else {
105 | predicates.add(builder.equal(mtPath.get(jpaUtil.attribute(mt, attr)), attrValue));
106 | }
107 | }
108 | }
109 | return predicates;
110 | }
111 |
112 | /*
113 | * Invoke byExample method for each not null x-to-one association when their pk is not set. This allows you to search entities based on an associated
114 | * entity's properties value.
115 | */
116 | @SuppressWarnings("unchecked")
117 | public , M2O extends Identifiable>> List byExampleOnXToOne(ManagedType mt, Root mtPath, T mtValue,
118 | SearchParameters sp, CriteriaBuilder builder) {
119 | List predicates = newArrayList();
120 | for (SingularAttribute super T, ?> attr : mt.getSingularAttributes()) {
121 | if (attr.getPersistentAttributeType() == MANY_TO_ONE || attr.getPersistentAttributeType() == ONE_TO_ONE) {
122 | M2O m2oValue = (M2O) jpaUtil.getValue(mtValue, mt.getAttribute(attr.getName()));
123 | Class m2oType = (Class) attr.getBindableJavaType();
124 | Path m2oPath = (Path) mtPath.get(attr);
125 | ManagedType m2oMt = em.getMetamodel().entity(m2oType);
126 | if (m2oValue != null) {
127 | if (m2oValue.isIdSet()) { // we have an id, let's restrict only on this field
128 | predicates.add(builder.equal(m2oPath.get("id"), m2oValue.getId()));
129 | } else {
130 | predicates.addAll(byExample(m2oMt, m2oPath, m2oValue, sp, builder));
131 | }
132 | }
133 | }
134 | }
135 | return predicates;
136 | }
137 |
138 | /*
139 | * Construct a join predicate on collection (eg many to many, List)
140 | */
141 | public List byExampleOnXToMany(ManagedType mt, Root mtPath, T mtValue, SearchParameters sp, CriteriaBuilder builder) {
142 | List predicates = newArrayList();
143 | for (PluralAttribute super T, ?, ?> pa : mt.getPluralAttributes()) {
144 | if (pa.getCollectionType() == PluralAttribute.CollectionType.LIST) {
145 | List> values = (List>) jpaUtil.getValue(mtValue, mt.getAttribute(pa.getName()));
146 | if (values != null && !values.isEmpty()) {
147 | if (sp.getUseAndInXToMany()) {
148 | if (values.size() > 3) {
149 | log.warn("Please note that using AND restriction on an Many to Many relationship requires as many joins as values");
150 | }
151 | for (Object value : values) {
152 | ListJoin join = mtPath.join(mt.getList(pa.getName()));
153 | predicates.add(join.in(value));
154 | }
155 | } else {
156 | ListJoin join = mtPath.join(mt.getList(pa.getName()));
157 | predicates.add(join.in(values));
158 | }
159 | }
160 | }
161 | }
162 | return predicates;
163 | }
164 | }
--------------------------------------------------------------------------------
/src/main/java/com/jaxio/jpa/querybyexample/ByFullTextUtil.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2015 JAXIO http://www.jaxio.com
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.jaxio.jpa.querybyexample;
17 |
18 | import javax.inject.Inject;
19 | import javax.inject.Named;
20 | import javax.inject.Singleton;
21 | import javax.persistence.Embeddable;
22 | import javax.persistence.EntityManager;
23 | import javax.persistence.PersistenceContext;
24 | import javax.persistence.criteria.CriteriaBuilder;
25 | import javax.persistence.criteria.Path;
26 | import javax.persistence.criteria.Predicate;
27 | import javax.persistence.criteria.Root;
28 | import javax.persistence.metamodel.ManagedType;
29 | import javax.persistence.metamodel.SingularAttribute;
30 | import java.io.Serializable;
31 | import java.util.List;
32 |
33 | import static com.google.common.collect.Lists.newArrayList;
34 | import static java.util.Collections.emptyList;
35 |
36 | /**
37 | * @author Nicolas Romanetti
38 | * @author Florent Ramière
39 | * @author Sébastien Péralta
40 | * @author Jean-Louis Boudart
41 | */
42 | @Named
43 | @Singleton
44 | public class ByFullTextUtil {
45 | @PersistenceContext
46 | private EntityManager em;
47 |
48 | @Inject
49 | protected HibernateSearchUtil hibernateSearchUtil;
50 | @Inject
51 | private JpaUtil jpaUtil;
52 |
53 | public > Predicate byFullText(Root root, CriteriaBuilder builder, SearchParameters sp, T entity,
54 | List> indexedAttributes) {
55 | if (!hasNonEmptyTerms(sp)) {
56 | return null;
57 | }
58 |
59 | if (jpaUtil.hasSimplePk(entity)) {
60 | return onSimplePrimaryKey(root, builder, sp, indexedAttributes);
61 | } else {
62 | return onCompositePrimaryKeys(root, builder, sp, indexedAttributes);
63 | }
64 | }
65 |
66 | private boolean hasNonEmptyTerms(SearchParameters sp) {
67 | for (TermSelector termSelector : sp.getTerms()) {
68 | if (termSelector.isNotEmpty()) {
69 | return true;
70 | }
71 | }
72 | return false;
73 | }
74 |
75 | private > Predicate onCompositePrimaryKeys(Root root, CriteriaBuilder builder, SearchParameters sp,
76 | List> properties) {
77 | List extends T> found = hibernateSearchUtil.find(root.getJavaType(), sp, properties);
78 | if (found == null) {
79 | return null;
80 | } else if (found.isEmpty()) {
81 | return builder.disjunction();
82 | }
83 |
84 | List predicates = newArrayList();
85 | for (T t : found) {
86 | predicates.add(byExampleOnEntity(root, t, sp, builder));
87 | }
88 | return jpaUtil.concatPredicate(sp, builder, jpaUtil.orPredicate(builder, predicates));
89 | }
90 |
91 | private Predicate onSimplePrimaryKey(Root root, CriteriaBuilder builder, SearchParameters sp, List> properties) {
92 | List ids = hibernateSearchUtil.findId(root.getJavaType(), sp, properties);
93 | if (ids == null) {
94 | return null;
95 | } else if (ids.isEmpty()) {
96 | return builder.disjunction();
97 | }
98 |
99 | return jpaUtil.concatPredicate(sp, builder, root.get("id").in(ids));
100 | }
101 |
102 | public > Predicate byExampleOnEntity(Root rootPath, T entityValue, SearchParameters sp, CriteriaBuilder builder) {
103 | if (entityValue == null) {
104 | return null;
105 | }
106 |
107 | Class type = rootPath.getModel().getBindableJavaType();
108 | ManagedType mt = em.getMetamodel().entity(type);
109 |
110 | List predicates = newArrayList();
111 | predicates.addAll(byExample(mt, rootPath, entityValue, sp, builder));
112 | predicates.addAll(byExampleOnCompositePk(rootPath, entityValue, sp, builder));
113 | return jpaUtil.orPredicate(builder, predicates);
114 | }
115 |
116 | protected > List byExampleOnCompositePk(Root root, T entity, SearchParameters sp, CriteriaBuilder builder) {
117 | String compositePropertyName = jpaUtil.compositePkPropertyName(entity);
118 | if (compositePropertyName == null) {
119 | return emptyList();
120 | } else {
121 | return newArrayList(byExampleOnEmbeddable(root.get(compositePropertyName), entity.getId(), sp, builder));
122 | }
123 | }
124 |
125 | public Predicate byExampleOnEmbeddable(Path embeddablePath, E embeddableValue, SearchParameters sp, CriteriaBuilder builder) {
126 | if (embeddableValue == null) {
127 | return null;
128 | }
129 |
130 | Class type = embeddablePath.getModel().getBindableJavaType();
131 | ManagedType mt = em.getMetamodel().embeddable(type); // note: calling .managedType() does not work
132 | return jpaUtil.orPredicate(builder, byExample(mt, embeddablePath, embeddableValue, sp, builder));
133 | }
134 |
135 | /*
136 | * Add a predicate for each simple property whose value is not null.
137 | */
138 | public List byExample(ManagedType mt, Path mtPath, T mtValue, SearchParameters sp, CriteriaBuilder builder) {
139 | List predicates = newArrayList();
140 | for (SingularAttribute super T, ?> attr : mt.getSingularAttributes()) {
141 | if (!isPrimaryKey(mt, attr)) {
142 | continue;
143 | }
144 |
145 | Object attrValue = jpaUtil.getValue(mtValue, attr);
146 | if (attrValue != null) {
147 | predicates.add(builder.equal(mtPath.get(jpaUtil.attribute(mt, attr)), attrValue));
148 | }
149 | }
150 | return predicates;
151 | }
152 |
153 | private boolean isPrimaryKey(ManagedType mt, SingularAttribute super T, ?> attr) {
154 | if (mt.getJavaType().getAnnotation(Embeddable.class) != null) {
155 | return true;
156 | }
157 | return jpaUtil.isPk(mt, attr);
158 | }
159 | }
--------------------------------------------------------------------------------
/src/main/java/com/jaxio/jpa/querybyexample/ByNamedQueryUtil.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2015 JAXIO http://www.jaxio.com
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.jaxio.jpa.querybyexample;
17 |
18 | import org.slf4j.Logger;
19 | import org.slf4j.LoggerFactory;
20 |
21 | import javax.inject.Inject;
22 | import javax.inject.Named;
23 | import javax.inject.Singleton;
24 | import javax.persistence.EntityManager;
25 | import javax.persistence.PersistenceContext;
26 | import javax.persistence.Query;
27 | import java.util.List;
28 | import java.util.Map;
29 | import java.util.Map.Entry;
30 |
31 | /**
32 | * Helper class to create named query supporting dynamic sort order and pagination.
33 | */
34 | @Named
35 | @Singleton
36 | public class ByNamedQueryUtil {
37 | private static final Logger log = LoggerFactory.getLogger(ByNamedQueryUtil.class);
38 |
39 | @PersistenceContext
40 | private EntityManager entityManager;
41 | @Inject
42 | private JpaUtil jpaUtil;
43 |
44 | public ByNamedQueryUtil() {
45 | }
46 |
47 | public ByNamedQueryUtil(EntityManager entityManager) {
48 | this.entityManager = entityManager;
49 | }
50 |
51 | protected EntityManager getEntityManager() {
52 | return entityManager;
53 | }
54 |
55 | public List findByNamedQuery(SearchParameters sp) {
56 | if (sp == null || !sp.hasNamedQuery()) {
57 | throw new IllegalArgumentException("searchParameters must be non null and must have a namedQuery");
58 | }
59 |
60 | Query query = entityManager.createNamedQuery(sp.getNamedQuery());
61 | String queryString = getQueryString(query);
62 |
63 | // append order by if needed
64 | if (queryString != null && sp.hasOrders()) {
65 | // create the sql restriction clausis
66 | StringBuilder orderClausis = new StringBuilder("order by ");
67 | boolean first = true;
68 | for (OrderBy orderBy : sp.getOrders()) {
69 | if (!first) {
70 | orderClausis.append(", ");
71 | }
72 | orderClausis.append(orderBy.getPath());
73 | orderClausis.append(orderBy.isOrderDesc() ? " desc" : " asc");
74 | first = false;
75 | }
76 |
77 | log.debug("appending: [{}] to {}", orderClausis, queryString);
78 |
79 | query = recreateQuery(query, queryString + " " + orderClausis.toString());
80 | }
81 |
82 | // pagination
83 | jpaUtil.applyPagination(query, sp);
84 |
85 | // named parameters
86 | setQueryParameters(query, sp);
87 |
88 | // execute
89 | @SuppressWarnings("unchecked")
90 | List result = query.getResultList();
91 |
92 | if (result != null) {
93 | log.debug("{} returned a List of size: {}", sp.getNamedQuery(), result.size());
94 | }
95 |
96 | return result;
97 | }
98 |
99 | @SuppressWarnings("unchecked")
100 | public T byNamedQuery(SearchParameters sp) {
101 | return (T) objectByNamedQuery(sp);
102 | }
103 |
104 | public Number numberByNamedQuery(SearchParameters sp) {
105 | return (Number) objectByNamedQuery(sp);
106 | }
107 |
108 | public Object objectByNamedQuery(SearchParameters sp) {
109 | if (sp == null || !sp.hasNamedQuery()) {
110 | throw new IllegalStateException("Invalid search template provided: could not determine which namedQuery to use");
111 | }
112 |
113 | Query query = entityManager.createNamedQuery(sp.getNamedQuery());
114 | String queryString = getQueryString(query);
115 |
116 | // append select count if needed
117 | if (queryString != null && queryString.toLowerCase().startsWith("from") && !queryString.toLowerCase().contains("count(")) {
118 | query = recreateQuery(query, "select count(*) " + queryString);
119 | }
120 |
121 | setQueryParameters(query, sp);
122 |
123 | log.debug("objectNamedQuery : {}", sp.toString());
124 |
125 | // execute
126 | Object result = query.getSingleResult();
127 |
128 | if (log.isDebugEnabled()) {
129 | log.debug("{} returned a {} object", sp.getNamedQuery(), result == null ? "null" : result.getClass());
130 | if (result instanceof Number) {
131 | log.debug("{} returned a number with value : {}", sp.getNamedQuery(), result);
132 | }
133 | }
134 |
135 | return result;
136 | }
137 |
138 | private void setQueryParameters(Query query, SearchParameters sp) {
139 | // add parameters for the named query
140 | for (Entry entrySet : sp.getNamedQueryParameters().entrySet()) {
141 | query.setParameter(entrySet.getKey(), entrySet.getValue());
142 | }
143 | }
144 |
145 | /**
146 | * If the named query has the "query" hint, it uses the hint value (which must be jpa QL) to create a new query and append to it the proper order by clause.
147 | */
148 | private String getQueryString(Query query) {
149 | Map hints = query.getHints();
150 | return hints != null ? (String) hints.get("query") : null;
151 | }
152 |
153 | private Query recreateQuery(Query current, String newSqlString) {
154 | Query result = entityManager.createQuery(newSqlString);
155 | for (Entry hint : current.getHints().entrySet()) {
156 | result.setHint(hint.getKey(), hint.getValue());
157 | }
158 | return result;
159 | }
160 | }
--------------------------------------------------------------------------------
/src/main/java/com/jaxio/jpa/querybyexample/ByPatternUtil.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2015 JAXIO http://www.jaxio.com
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.jaxio.jpa.querybyexample;
17 |
18 | import javax.inject.Inject;
19 | import javax.inject.Named;
20 | import javax.inject.Singleton;
21 | import javax.persistence.EntityManager;
22 | import javax.persistence.PersistenceContext;
23 | import javax.persistence.criteria.CriteriaBuilder;
24 | import javax.persistence.criteria.Expression;
25 | import javax.persistence.criteria.Predicate;
26 | import javax.persistence.criteria.Root;
27 | import javax.persistence.metamodel.EntityType;
28 | import javax.persistence.metamodel.SingularAttribute;
29 | import java.util.List;
30 |
31 | import static com.google.common.collect.Lists.newArrayList;
32 | import static javax.persistence.metamodel.Attribute.PersistentAttributeType.MANY_TO_ONE;
33 | import static javax.persistence.metamodel.Attribute.PersistentAttributeType.ONE_TO_ONE;
34 |
35 | @Named
36 | @Singleton
37 | public class ByPatternUtil {
38 | @PersistenceContext
39 | private EntityManager em;
40 | @Inject
41 | private JpaUtil jpaUtil;
42 |
43 | /*
44 | * Lookup entities having at least one String attribute matching the passed sp's pattern
45 | */
46 | @SuppressWarnings("unchecked")
47 | public Predicate byPattern(Root root, CriteriaBuilder builder, SearchParameters sp, Class type) {
48 | if (!sp.hasSearchPattern()) {
49 | return null;
50 | }
51 |
52 | List predicates = newArrayList();
53 | EntityType entity = em.getMetamodel().entity(type);
54 | String pattern = sp.getSearchPattern();
55 |
56 | for (SingularAttribute super T, ?> attr : entity.getSingularAttributes()) {
57 | if (attr.getPersistentAttributeType() == MANY_TO_ONE || attr.getPersistentAttributeType() == ONE_TO_ONE) {
58 | continue;
59 | }
60 |
61 | if (attr.getJavaType() == String.class) {
62 | predicates.add(jpaUtil.stringPredicate((Expression) root.get(jpaUtil.attribute(entity, attr)), pattern, sp, builder));
63 | }
64 | }
65 |
66 | return jpaUtil.orPredicate(builder, predicates);
67 | }
68 | }
--------------------------------------------------------------------------------
/src/main/java/com/jaxio/jpa/querybyexample/ByPropertySelectorUtil.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2015 JAXIO http://www.jaxio.com
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.jaxio.jpa.querybyexample;
17 |
18 | import javax.inject.Inject;
19 | import javax.inject.Named;
20 | import javax.inject.Singleton;
21 | import javax.persistence.criteria.CriteriaBuilder;
22 | import javax.persistence.criteria.Path;
23 | import javax.persistence.criteria.Predicate;
24 | import javax.persistence.criteria.Root;
25 | import java.io.Serializable;
26 | import java.util.List;
27 |
28 | import static com.google.common.collect.Lists.newArrayList;
29 | import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
30 |
31 | /**
32 | * Helper to create a predicate out of {@link PropertySelector}s.
33 | */
34 | @Named
35 | @Singleton
36 | public class ByPropertySelectorUtil {
37 |
38 | @Inject
39 | private JpaUtil jpaUtil;
40 |
41 | @SuppressWarnings("unchecked")
42 | public Predicate byPropertySelectors(Root root, CriteriaBuilder builder, SearchParameters sp) {
43 | List predicates = newArrayList();
44 |
45 | for (PropertySelector, ?> selector : sp.getProperties()) {
46 | if (selector.isBoolean()) {
47 | byBooleanSelector(root, builder, predicates, sp, (PropertySelector super E, Boolean>) selector);
48 | } else if (selector.isString()) {
49 | byStringSelector(root, builder, predicates, sp, (PropertySelector super E, String>) selector);
50 | } else {
51 | byObjectSelector(root, builder, predicates, sp, (PropertySelector super E, ?>) selector);
52 | }
53 | }
54 | return jpaUtil.concatPredicate(sp, builder, predicates);
55 | }
56 |
57 | private void byBooleanSelector(Root root, CriteriaBuilder builder, List predicates, SearchParameters sp,
58 | PropertySelector super E, Boolean> selector) {
59 | if (selector.isNotEmpty()) {
60 | List selectorPredicates = newArrayList();
61 |
62 | for (Boolean selection : selector.getSelected()) {
63 | Path path = jpaUtil.getPath(root, selector.getAttributes());
64 | if (selection == null) {
65 | selectorPredicates.add(builder.isNull(path));
66 | } else {
67 | selectorPredicates.add(selection ? builder.isTrue(path) : builder.isFalse(path));
68 | }
69 | }
70 | if (selector.isOrMode()) {
71 | predicates.add(jpaUtil.orPredicate(builder, selectorPredicates));
72 | } else {
73 | predicates.add(jpaUtil.andPredicate(builder, selectorPredicates));
74 | }
75 | }
76 | }
77 |
78 | private void byStringSelector(Root root, CriteriaBuilder builder, List predicates, SearchParameters sp,
79 | PropertySelector super E, String> selector) {
80 | if (selector.isNotEmpty()) {
81 | List selectorPredicates = newArrayList();
82 |
83 | for (String selection : selector.getSelected()) {
84 | Path path = jpaUtil.getPath(root, selector.getAttributes());
85 | selectorPredicates.add(jpaUtil.stringPredicate(path, selection, selector.getSearchMode(), sp, builder));
86 | }
87 | if (selector.isOrMode()) {
88 | predicates.add(jpaUtil.orPredicate(builder, selectorPredicates));
89 | } else {
90 | predicates.add(jpaUtil.andPredicate(builder, selectorPredicates));
91 | }
92 | }
93 | }
94 |
95 | private void byObjectSelector(Root root, CriteriaBuilder builder, List predicates, SearchParameters sp,
96 | PropertySelector super E, ?> selector) {
97 | if (selector.isNotEmpty()) {
98 | if (selector.isOrMode()) {
99 | byObjectOrModeSelector(root, builder, predicates, sp, selector);
100 | } else {
101 | byObjectAndModeSelector(root, builder, predicates, sp, selector);
102 | }
103 | } else if (selector.isNotIncludingNullSet()) {
104 | predicates.add(builder.isNotNull(jpaUtil.getPath(root, selector.getAttributes())));
105 | }
106 | }
107 |
108 | private void byObjectOrModeSelector(Root root, CriteriaBuilder builder, List predicates, SearchParameters sp,
109 | PropertySelector super E, ?> selector) {
110 | List selectorPredicates = newArrayList();
111 | Path> path = jpaUtil.getPath(root, selector.getAttributes());
112 | List> selected = selector.getSelected();
113 | if (selected.contains(null)) {
114 | selected = newArrayList(selector.getSelected());
115 | selected.remove(null);
116 | selectorPredicates.add(builder.isNull(path));
117 | }
118 | if (isNotEmpty(selected)) {
119 | if (selected.get(0) instanceof Identifiable) {
120 | List ids = newArrayList();
121 | for (Object selection : selected) {
122 | ids.add(((Identifiable>) selection).getId());
123 | }
124 | selectorPredicates.add(path.get("id").in(ids));
125 | } else {
126 | selectorPredicates.add(path.in(selected));
127 | }
128 | }
129 | predicates.add(jpaUtil.orPredicate(builder, selectorPredicates));
130 | }
131 |
132 | private void byObjectAndModeSelector(Root root, CriteriaBuilder builder, List predicates, SearchParameters sp,
133 | PropertySelector super E, ?> selector) {
134 | List selectorPredicates = newArrayList();
135 | List> selected = selector.getSelected();
136 | if (selected.contains(null)) {
137 | selected = newArrayList(selector.getSelected());
138 | selected.remove(null);
139 | selectorPredicates.add(builder.isNull(jpaUtil.getPath(root, selector.getAttributes())));
140 | }
141 | for (Object selection : selected) {
142 | Path> path = jpaUtil.getPath(root, selector.getAttributes());
143 | if (selection instanceof Identifiable) {
144 | selectorPredicates.add(builder.equal(path.get("id"), ((Identifiable>) selection).getId()));
145 | } else {
146 | selectorPredicates.add(builder.equal(path, selection));
147 | }
148 | }
149 | predicates.add(jpaUtil.andPredicate(builder, selectorPredicates));
150 | }
151 | }
--------------------------------------------------------------------------------
/src/main/java/com/jaxio/jpa/querybyexample/ByRangeUtil.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2015 JAXIO http://www.jaxio.com
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.jaxio.jpa.querybyexample;
17 |
18 | import javax.inject.Inject;
19 | import javax.inject.Named;
20 | import javax.inject.Singleton;
21 | import javax.persistence.criteria.CriteriaBuilder;
22 | import javax.persistence.criteria.Path;
23 | import javax.persistence.criteria.Predicate;
24 | import javax.persistence.criteria.Root;
25 | import java.util.List;
26 |
27 | import static com.google.common.collect.Lists.newArrayList;
28 | import static java.lang.Boolean.FALSE;
29 | import static java.lang.Boolean.TRUE;
30 |
31 | /**
32 | * Helper to create a predicate out of {@link Range}s.
33 | */
34 | @SuppressWarnings("unchecked")
35 | @Named
36 | @Singleton
37 | public class ByRangeUtil {
38 |
39 | @Inject
40 | private JpaUtil jpaUtil;
41 |
42 | public Predicate byRanges(Root root, CriteriaBuilder builder, SearchParameters sp, Class type) {
43 | List> ranges = sp.getRanges();
44 | List predicates = newArrayList();
45 | for (Range, ?> r : ranges) {
46 | Range range = (Range) r;
47 | if (range.isSet()) {
48 | Predicate rangePredicate = buildRangePredicate(range, root, builder);
49 | if (rangePredicate != null) {
50 | predicates.add(rangePredicate);
51 | }
52 | }
53 | }
54 |
55 | return jpaUtil.concatPredicate(sp, builder, predicates);
56 | }
57 |
58 | private static , E> Predicate buildRangePredicate(Range range, Root root, CriteriaBuilder builder) {
59 | Predicate rangePredicate = null;
60 | Path path = JpaUtil.getInstance().getPath(root, range.getAttributes());
61 | if (range.isBetween()) {
62 | rangePredicate = builder.between(path, range.getFrom(), range.getTo());
63 | } else if (range.isFromSet()) {
64 | rangePredicate = builder.greaterThanOrEqualTo(path, range.getFrom());
65 | } else if (range.isToSet()) {
66 | rangePredicate = builder.lessThanOrEqualTo(path, range.getTo());
67 | }
68 |
69 | if (rangePredicate != null) {
70 | if (!range.isIncludeNullSet() || range.getIncludeNull() == FALSE) {
71 | return rangePredicate;
72 | } else {
73 | return builder.or(rangePredicate, builder.isNull(path));
74 | }
75 | } else {
76 | // no from/to is set, but include null or not could be:
77 | if (TRUE == range.getIncludeNull()) {
78 | return builder.isNull(path);
79 | } else if (FALSE == range.getIncludeNull()) {
80 | return builder.isNotNull(path);
81 | }
82 | }
83 | return null;
84 | }
85 | }
--------------------------------------------------------------------------------
/src/main/java/com/jaxio/jpa/querybyexample/DefaultLuceneQueryBuilder.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2015 JAXIO http://www.jaxio.com
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.jaxio.jpa.querybyexample;
17 |
18 | import org.apache.lucene.analysis.miscellaneous.ASCIIFoldingFilter;
19 | import org.apache.lucene.queryparser.classic.QueryParser;
20 | import org.apache.lucene.search.Query;
21 | import org.hibernate.search.jpa.FullTextEntityManager;
22 | import org.slf4j.Logger;
23 | import org.slf4j.LoggerFactory;
24 |
25 | import javax.persistence.metamodel.SingularAttribute;
26 | import java.util.List;
27 |
28 | import static com.google.common.base.Preconditions.checkArgument;
29 | import static com.google.common.base.Throwables.propagate;
30 | import static com.google.common.collect.Lists.newArrayList;
31 | import static org.apache.commons.lang.StringUtils.*;
32 | import static org.apache.lucene.queryparser.classic.QueryParser.escape;
33 |
34 | public class DefaultLuceneQueryBuilder implements LuceneQueryBuilder {
35 |
36 | private static final long serialVersionUID = 1L;
37 | private static final Logger log = LoggerFactory.getLogger(DefaultLuceneQueryBuilder.class);
38 |
39 | private static final String SPACES_OR_PUNCTUATION = "\\p{Punct}|\\p{Blank}";
40 |
41 | @Override
42 | public Query build(FullTextEntityManager fullTextEntityManager, SearchParameters searchParameters, List> availableProperties) {
43 | List clauses = getAllClauses(searchParameters, searchParameters.getTerms(), availableProperties);
44 |
45 | StringBuilder query = new StringBuilder();
46 | query.append("+(");
47 | for (String clause : clauses) {
48 | if (query.length() > 2) {
49 | query.append(" AND ");
50 | }
51 | query.append(clause);
52 | }
53 | query.append(")");
54 |
55 | if (query.length() == 3) {
56 | return null;
57 | }
58 | log.debug("Lucene query: {}", query);
59 | try {
60 | return new QueryParser(availableProperties.get(0).getName(), fullTextEntityManager.getSearchFactory().getAnalyzer("custom"))
61 | .parse(query.toString());
62 | } catch (Exception e) {
63 | throw propagate(e);
64 | }
65 | }
66 |
67 | private List getAllClauses(SearchParameters sp, List terms, List> availableProperties) {
68 | List clauses = newArrayList();
69 | for (TermSelector term : terms) {
70 | if (term.isNotEmpty()) {
71 | String clause = getClause(sp, term.getSelected(), term.getAttribute(), term.isOrMode(), availableProperties);
72 | if (isNotBlank(clause)) {
73 | clauses.add(clause);
74 | }
75 | }
76 | }
77 | return clauses;
78 | }
79 |
80 | private String getClause(SearchParameters sp, List terms, SingularAttribute, ?> property, boolean orMode,
81 | List> availableProperties) {
82 | if (property != null) {
83 | checkArgument(availableProperties.contains(property), property + " is not indexed");
84 | StringBuilder subQuery = new StringBuilder();
85 | if (terms != null) {
86 | subQuery.append("(");
87 | for (String wordWithSpacesOrPunctuation : terms) {
88 | if (isBlank(wordWithSpacesOrPunctuation)) {
89 | continue;
90 | }
91 | List wordElements = newArrayList();
92 | for (String str : wordWithSpacesOrPunctuation.split(SPACES_OR_PUNCTUATION)) {
93 | if (isNotBlank(str)) {
94 | wordElements.add(str);
95 | }
96 | }
97 | if (!wordElements.isEmpty()) {
98 | if (subQuery.length() > 1) {
99 | subQuery.append(" ").append(orMode ? "OR" : "AND").append(" ");
100 | }
101 | subQuery.append(buildSubQuery(property, wordElements, sp));
102 | }
103 | }
104 | subQuery.append(")");
105 | }
106 | if (subQuery.length() > 2) {
107 | return subQuery.toString();
108 | }
109 | } else {
110 | return getOnAnyClause(sp, terms, availableProperties, orMode, availableProperties);
111 | }
112 | return null;
113 | }
114 |
115 | private String buildSubQuery(SingularAttribute, ?> property, List terms, SearchParameters sp) {
116 | StringBuilder subQuery = new StringBuilder();
117 | subQuery.append("(");
118 | for (String term : terms) {
119 | if (subQuery.length() > 1) {
120 | subQuery.append(" AND ");
121 | }
122 | if (sp.getSearchSimilarity() != null) {
123 | subQuery.append(property.getName() + ":" + escapeForFuzzy(lowerCase(term)) + "~" + sp.getSearchSimilarity());
124 | } else {
125 | subQuery.append(property.getName() + ":" + escape(lowerCase(term)));
126 | }
127 | }
128 | subQuery.append(")");
129 | return subQuery.toString();
130 | }
131 |
132 | private String getOnAnyClause(SearchParameters sp, List terms, List> properties, boolean orMode,
133 | List> availableProperties) {
134 | List subClauses = newArrayList();
135 | for (SingularAttribute, ?> property : properties) {
136 | String clause = getClause(sp, terms, property, orMode, availableProperties);
137 | if (isNotBlank(clause)) {
138 | subClauses.add(clause);
139 | }
140 | }
141 | if (subClauses.isEmpty()) {
142 | return null;
143 | }
144 | if (subClauses.size() > 1) {
145 | StringBuilder subQuery = new StringBuilder();
146 | subQuery.append("(");
147 | for (String subClause : subClauses) {
148 | if (subQuery.length() > 1) {
149 | subQuery.append(" OR ");
150 | }
151 | subQuery.append(subClause);
152 | }
153 | subQuery.append(")");
154 | return subQuery.toString();
155 | } else {
156 | return subClauses.get(0);
157 | }
158 | }
159 |
160 | /**
161 | * Apply same filtering as "custom" analyzer. Lowercase is done by QueryParser for fuzzy search.
162 | *
163 | * @param word word
164 | * @return word escaped
165 | */
166 | private String escapeForFuzzy(String word) {
167 | int length = word.length();
168 | char[] tmp = new char[length * 4];
169 | length = ASCIIFoldingFilter.foldToASCII(word.toCharArray(), 0, tmp, 0, length);
170 | return new String(tmp, 0, length);
171 | }
172 | }
173 |
--------------------------------------------------------------------------------
/src/main/java/com/jaxio/jpa/querybyexample/EntityGraphLoader.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2015 JAXIO http://www.jaxio.com
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.jaxio.jpa.querybyexample;
17 |
18 | import org.springframework.transaction.annotation.Transactional;
19 |
20 | import java.io.Serializable;
21 | import java.util.Collection;
22 |
23 | /**
24 | * The EntityGraphLoader is used to load within a single read-only transaction all the desired associations that
25 | * are normally lazily loaded.
26 | */
27 | public abstract class EntityGraphLoader, PK extends Serializable> {
28 |
29 | protected GenericRepository repository;
30 |
31 | // required by cglib to create a proxy around the object as we are using the @Transactional annotation
32 | public EntityGraphLoader() {
33 | }
34 |
35 | public EntityGraphLoader(GenericRepository repository) {
36 | this.repository = repository;
37 | }
38 |
39 | /*
40 | * Get the entity by id and load its graph using loadGraph.
41 | */
42 | @Transactional(readOnly = true)
43 | public T getById(PK pk) {
44 | T entity = repository.getById(pk);
45 | loadGraph(entity);
46 | return entity;
47 | }
48 |
49 | /*
50 | * Merge the passed entity and load the graph of the merged entity using loadGraph.
51 | */
52 | @Transactional(readOnly = true)
53 | public T merge(T entity) {
54 | T mergedEntity = repository.merge(entity);
55 | loadGraph(mergedEntity);
56 | return mergedEntity;
57 | }
58 |
59 | /*
60 | * Load whatever is needed in the graph of the passed entity, for example x-to-many collection, x-to-one object, etc.
61 | */
62 | public abstract void loadGraph(T entity);
63 |
64 | /*
65 | * Load the passed 'x-to-many' association.
66 | */
67 | protected void loadCollection(Collection> collection) {
68 | if (collection != null) {
69 | collection.size();
70 | }
71 | }
72 |
73 | /*
74 | * Load the passed 'x-to-one' association.
75 | */
76 | protected void loadSingular(Object association) {
77 | if (association != null) {
78 | association.toString();
79 | }
80 | }
81 | }
--------------------------------------------------------------------------------
/src/main/java/com/jaxio/jpa/querybyexample/GenericRepository.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2015 JAXIO http://www.jaxio.com
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.jaxio.jpa.querybyexample;
17 |
18 | import org.hibernate.search.annotations.Field;
19 | import org.slf4j.Logger;
20 | import org.slf4j.LoggerFactory;
21 | import org.springframework.transaction.annotation.Transactional;
22 |
23 | import javax.annotation.PostConstruct;
24 | import javax.inject.Inject;
25 | import javax.persistence.*;
26 | import javax.persistence.criteria.*;
27 | import javax.persistence.metamodel.Attribute;
28 | import javax.persistence.metamodel.EntityType;
29 | import javax.persistence.metamodel.PluralAttribute;
30 | import javax.persistence.metamodel.SingularAttribute;
31 | import java.io.Serializable;
32 | import java.lang.reflect.Method;
33 | import java.util.List;
34 |
35 | import static com.google.common.base.Preconditions.checkNotNull;
36 | import static com.google.common.collect.Lists.newArrayList;
37 |
38 | /**
39 | * JPA 2 {@link GenericRepository} implementation
40 | */
41 | public abstract class GenericRepository, PK extends Serializable> {
42 | @Inject
43 | protected ByExampleUtil byExampleUtil;
44 | @Inject
45 | protected ByPatternUtil byPatternUtil;
46 | @Inject
47 | protected ByRangeUtil byRangeUtil;
48 | @Inject
49 | protected ByNamedQueryUtil byNamedQueryUtil;
50 | @Inject
51 | protected ByPropertySelectorUtil byPropertySelectorUtil;
52 | @Inject
53 | protected OrderByUtil orderByUtil;
54 | @Inject
55 | protected MetamodelUtil metamodelUtil;
56 | @Inject
57 | private JpaUtil jpaUtil;
58 | @Inject
59 | protected ByFullTextUtil byFullTextUtil;
60 | protected List> indexedAttributes;
61 | @PersistenceContext
62 | protected EntityManager entityManager;
63 | protected Class type;
64 | protected Logger log;
65 | protected String cacheRegion;
66 |
67 | /*
68 | * This constructor needs the real type of the generic type E so it can be given to the {@link javax.persistence.EntityManager}.
69 | */
70 | public GenericRepository(Class type) {
71 | this.type = type;
72 | this.log = LoggerFactory.getLogger(getClass());
73 | this.cacheRegion = type.getCanonicalName();
74 | }
75 |
76 | @PostConstruct
77 | protected void init() {
78 | this.indexedAttributes = buildIndexedAttributes(type);
79 | }
80 |
81 | public Class getType() {
82 | return type;
83 | }
84 |
85 | /**
86 | * Create a new instance of the repository type.
87 | *
88 | * @return a new instance with no property set.
89 | */
90 | public abstract E getNew();
91 |
92 | /**
93 | * Creates a new instance and initializes it with some default values.
94 | *
95 | * @return a new instance initialized with default values.
96 | */
97 | public E getNewWithDefaults() {
98 | return getNew();
99 | }
100 |
101 | /**
102 | * Gets from the repository the E entity instance.
103 | *