├── .gitignore ├── LICENSE ├── README ├── build.gradle ├── out ├── production │ └── hibernate-query-dsl │ │ └── br │ │ └── com │ │ └── caelum │ │ └── hibernatequerydsl │ │ ├── ActiveCollection.scala │ │ ├── ComparisonCallback.scala │ │ ├── Expression.scala │ │ ├── InvocationMemorizingCallback.scala │ │ ├── OrderThis.scala │ │ ├── PimpedCriteria.scala │ │ ├── PimpedQuery.scala │ │ └── PimpedSession.scala └── test │ └── hibernate-query-dsl │ ├── br │ └── com │ │ └── caelum │ │ └── hibernatequerydsl │ │ ├── ActiveCollectionAcceptanceTest.scala │ │ ├── PimpedSessionTest.scala │ │ ├── TestingTest.scala │ │ └── TypeSafeAcceptanceTest.scala │ └── hibernate.cfg.xml └── src ├── main └── scala │ └── br │ └── com │ └── caelum │ └── hibernatequerydsl │ ├── ActiveCollection.scala │ ├── ComparisonCallback.scala │ ├── Expression.scala │ ├── InvocationMemorizingCallback.scala │ ├── OrderThis.scala │ ├── PimpedCriteria.scala │ ├── PimpedQuery.scala │ ├── PimpedSession.scala │ └── Transformer.scala └── test ├── resources └── hibernate.cfg.xml └── scala └── br └── com └── caelum └── hibernatequerydsl ├── ActiveCollectionAcceptanceTest.scala ├── Address.java ├── PimpedSessionTest.scala ├── StreetWithName.java ├── TestingTest.scala ├── TypeSafeAcceptanceTest.scala └── User.java /.gitignore: -------------------------------------------------------------------------------- 1 | bin 2 | generated 3 | target 4 | *.class 5 | .gradle 6 | .classpath 7 | .project 8 | .settings 9 | .classpath.old 10 | build 11 | .scala_dependencies 12 | *.iml 13 | *.ipr 14 | *.iws 15 | .DS_Store 16 | 17 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU LESSER GENERAL PUBLIC LICENSE 2 | Version 2.1, February 1999 3 | 4 | Copyright (C) 1991, 1999 Free Software Foundation, Inc. 5 | 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | [This is the first released version of the Lesser GPL. It also counts 10 | as the successor of the GNU Library Public License, version 2, hence 11 | the version number 2.1.] 12 | 13 | Preamble 14 | 15 | The licenses for most software are designed to take away your 16 | freedom to share and change it. By contrast, the GNU General Public 17 | Licenses are intended to guarantee your freedom to share and change 18 | free software--to make sure the software is free for all its users. 19 | 20 | This license, the Lesser General Public License, applies to some 21 | specially designated software packages--typically libraries--of the 22 | Free Software Foundation and other authors who decide to use it. You 23 | can use it too, but we suggest you first think carefully about whether 24 | this license or the ordinary General Public License is the better 25 | strategy to use in any particular case, based on the explanations below. 26 | 27 | When we speak of free software, we are referring to freedom of use, 28 | not price. Our General Public Licenses are designed to make sure that 29 | you have the freedom to distribute copies of free software (and charge 30 | for this service if you wish); that you receive source code or can get 31 | it if you want it; that you can change the software and use pieces of 32 | it in new free programs; and that you are informed that you can do 33 | these things. 34 | 35 | To protect your rights, we need to make restrictions that forbid 36 | distributors to deny you these rights or to ask you to surrender these 37 | rights. These restrictions translate to certain responsibilities for 38 | you if you distribute copies of the library or if you modify it. 39 | 40 | For example, if you distribute copies of the library, whether gratis 41 | or for a fee, you must give the recipients all the rights that we gave 42 | you. You must make sure that they, too, receive or can get the source 43 | code. If you link other code with the library, you must provide 44 | complete object files to the recipients, so that they can relink them 45 | with the library after making changes to the library and recompiling 46 | it. And you must show them these terms so they know their rights. 47 | 48 | We protect your rights with a two-step method: (1) we copyright the 49 | library, and (2) we offer you this license, which gives you legal 50 | permission to copy, distribute and/or modify the library. 51 | 52 | To protect each distributor, we want to make it very clear that 53 | there is no warranty for the free library. Also, if the library is 54 | modified by someone else and passed on, the recipients should know 55 | that what they have is not the original version, so that the original 56 | author's reputation will not be affected by problems that might be 57 | introduced by others. 58 | 59 | Finally, software patents pose a constant threat to the existence of 60 | any free program. We wish to make sure that a company cannot 61 | effectively restrict the users of a free program by obtaining a 62 | restrictive license from a patent holder. Therefore, we insist that 63 | any patent license obtained for a version of the library must be 64 | consistent with the full freedom of use specified in this license. 65 | 66 | Most GNU software, including some libraries, is covered by the 67 | ordinary GNU General Public License. This license, the GNU Lesser 68 | General Public License, applies to certain designated libraries, and 69 | is quite different from the ordinary General Public License. We use 70 | this license for certain libraries in order to permit linking those 71 | libraries into non-free programs. 72 | 73 | When a program is linked with a library, whether statically or using 74 | a shared library, the combination of the two is legally speaking a 75 | combined work, a derivative of the original library. The ordinary 76 | General Public License therefore permits such linking only if the 77 | entire combination fits its criteria of freedom. The Lesser General 78 | Public License permits more lax criteria for linking other code with 79 | the library. 80 | 81 | We call this license the "Lesser" General Public License because it 82 | does Less to protect the user's freedom than the ordinary General 83 | Public License. It also provides other free software developers Less 84 | of an advantage over competing non-free programs. These disadvantages 85 | are the reason we use the ordinary General Public License for many 86 | libraries. However, the Lesser license provides advantages in certain 87 | special circumstances. 88 | 89 | For example, on rare occasions, there may be a special need to 90 | encourage the widest possible use of a certain library, so that it becomes 91 | a de-facto standard. To achieve this, non-free programs must be 92 | allowed to use the library. A more frequent case is that a free 93 | library does the same job as widely used non-free libraries. In this 94 | case, there is little to gain by limiting the free library to free 95 | software only, so we use the Lesser General Public License. 96 | 97 | In other cases, permission to use a particular library in non-free 98 | programs enables a greater number of people to use a large body of 99 | free software. For example, permission to use the GNU C Library in 100 | non-free programs enables many more people to use the whole GNU 101 | operating system, as well as its variant, the GNU/Linux operating 102 | system. 103 | 104 | Although the Lesser General Public License is Less protective of the 105 | users' freedom, it does ensure that the user of a program that is 106 | linked with the Library has the freedom and the wherewithal to run 107 | that program using a modified version of the Library. 108 | 109 | The precise terms and conditions for copying, distribution and 110 | modification follow. Pay close attention to the difference between a 111 | "work based on the library" and a "work that uses the library". The 112 | former contains code derived from the library, whereas the latter must 113 | be combined with the library in order to run. 114 | 115 | GNU LESSER GENERAL PUBLIC LICENSE 116 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 117 | 118 | 0. This License Agreement applies to any software library or other 119 | program which contains a notice placed by the copyright holder or 120 | other authorized party saying it may be distributed under the terms of 121 | this Lesser General Public License (also called "this License"). 122 | Each licensee is addressed as "you". 123 | 124 | A "library" means a collection of software functions and/or data 125 | prepared so as to be conveniently linked with application programs 126 | (which use some of those functions and data) to form executables. 127 | 128 | The "Library", below, refers to any such software library or work 129 | which has been distributed under these terms. A "work based on the 130 | Library" means either the Library or any derivative work under 131 | copyright law: that is to say, a work containing the Library or a 132 | portion of it, either verbatim or with modifications and/or translated 133 | straightforwardly into another language. (Hereinafter, translation is 134 | included without limitation in the term "modification".) 135 | 136 | "Source code" for a work means the preferred form of the work for 137 | making modifications to it. For a library, complete source code means 138 | all the source code for all modules it contains, plus any associated 139 | interface definition files, plus the scripts used to control compilation 140 | and installation of the library. 141 | 142 | Activities other than copying, distribution and modification are not 143 | covered by this License; they are outside its scope. The act of 144 | running a program using the Library is not restricted, and output from 145 | such a program is covered only if its contents constitute a work based 146 | on the Library (independent of the use of the Library in a tool for 147 | writing it). Whether that is true depends on what the Library does 148 | and what the program that uses the Library does. 149 | 150 | 1. You may copy and distribute verbatim copies of the Library's 151 | complete source code as you receive it, in any medium, provided that 152 | you conspicuously and appropriately publish on each copy an 153 | appropriate copyright notice and disclaimer of warranty; keep intact 154 | all the notices that refer to this License and to the absence of any 155 | warranty; and distribute a copy of this License along with the 156 | Library. 157 | 158 | You may charge a fee for the physical act of transferring a copy, 159 | and you may at your option offer warranty protection in exchange for a 160 | fee. 161 | 162 | 2. You may modify your copy or copies of the Library or any portion 163 | of it, thus forming a work based on the Library, and copy and 164 | distribute such modifications or work under the terms of Section 1 165 | above, provided that you also meet all of these conditions: 166 | 167 | a) The modified work must itself be a software library. 168 | 169 | b) You must cause the files modified to carry prominent notices 170 | stating that you changed the files and the date of any change. 171 | 172 | c) You must cause the whole of the work to be licensed at no 173 | charge to all third parties under the terms of this License. 174 | 175 | d) If a facility in the modified Library refers to a function or a 176 | table of data to be supplied by an application program that uses 177 | the facility, other than as an argument passed when the facility 178 | is invoked, then you must make a good faith effort to ensure that, 179 | in the event an application does not supply such function or 180 | table, the facility still operates, and performs whatever part of 181 | its purpose remains meaningful. 182 | 183 | (For example, a function in a library to compute square roots has 184 | a purpose that is entirely well-defined independent of the 185 | application. Therefore, Subsection 2d requires that any 186 | application-supplied function or table used by this function must 187 | be optional: if the application does not supply it, the square 188 | root function must still compute square roots.) 189 | 190 | These requirements apply to the modified work as a whole. If 191 | identifiable sections of that work are not derived from the Library, 192 | and can be reasonably considered independent and separate works in 193 | themselves, then this License, and its terms, do not apply to those 194 | sections when you distribute them as separate works. But when you 195 | distribute the same sections as part of a whole which is a work based 196 | on the Library, the distribution of the whole must be on the terms of 197 | this License, whose permissions for other licensees extend to the 198 | entire whole, and thus to each and every part regardless of who wrote 199 | it. 200 | 201 | Thus, it is not the intent of this section to claim rights or contest 202 | your rights to work written entirely by you; rather, the intent is to 203 | exercise the right to control the distribution of derivative or 204 | collective works based on the Library. 205 | 206 | In addition, mere aggregation of another work not based on the Library 207 | with the Library (or with a work based on the Library) on a volume of 208 | a storage or distribution medium does not bring the other work under 209 | the scope of this License. 210 | 211 | 3. You may opt to apply the terms of the ordinary GNU General Public 212 | License instead of this License to a given copy of the Library. To do 213 | this, you must alter all the notices that refer to this License, so 214 | that they refer to the ordinary GNU General Public License, version 2, 215 | instead of to this License. (If a newer version than version 2 of the 216 | ordinary GNU General Public License has appeared, then you can specify 217 | that version instead if you wish.) Do not make any other change in 218 | these notices. 219 | 220 | Once this change is made in a given copy, it is irreversible for 221 | that copy, so the ordinary GNU General Public License applies to all 222 | subsequent copies and derivative works made from that copy. 223 | 224 | This option is useful when you wish to copy part of the code of 225 | the Library into a program that is not a library. 226 | 227 | 4. You may copy and distribute the Library (or a portion or 228 | derivative of it, under Section 2) in object code or executable form 229 | under the terms of Sections 1 and 2 above provided that you accompany 230 | it with the complete corresponding machine-readable source code, which 231 | must be distributed under the terms of Sections 1 and 2 above on a 232 | medium customarily used for software interchange. 233 | 234 | If distribution of object code is made by offering access to copy 235 | from a designated place, then offering equivalent access to copy the 236 | source code from the same place satisfies the requirement to 237 | distribute the source code, even though third parties are not 238 | compelled to copy the source along with the object code. 239 | 240 | 5. A program that contains no derivative of any portion of the 241 | Library, but is designed to work with the Library by being compiled or 242 | linked with it, is called a "work that uses the Library". Such a 243 | work, in isolation, is not a derivative work of the Library, and 244 | therefore falls outside the scope of this License. 245 | 246 | However, linking a "work that uses the Library" with the Library 247 | creates an executable that is a derivative of the Library (because it 248 | contains portions of the Library), rather than a "work that uses the 249 | library". The executable is therefore covered by this License. 250 | Section 6 states terms for distribution of such executables. 251 | 252 | When a "work that uses the Library" uses material from a header file 253 | that is part of the Library, the object code for the work may be a 254 | derivative work of the Library even though the source code is not. 255 | Whether this is true is especially significant if the work can be 256 | linked without the Library, or if the work is itself a library. The 257 | threshold for this to be true is not precisely defined by law. 258 | 259 | If such an object file uses only numerical parameters, data 260 | structure layouts and accessors, and small macros and small inline 261 | functions (ten lines or less in length), then the use of the object 262 | file is unrestricted, regardless of whether it is legally a derivative 263 | work. (Executables containing this object code plus portions of the 264 | Library will still fall under Section 6.) 265 | 266 | Otherwise, if the work is a derivative of the Library, you may 267 | distribute the object code for the work under the terms of Section 6. 268 | Any executables containing that work also fall under Section 6, 269 | whether or not they are linked directly with the Library itself. 270 | 271 | 6. As an exception to the Sections above, you may also combine or 272 | link a "work that uses the Library" with the Library to produce a 273 | work containing portions of the Library, and distribute that work 274 | under terms of your choice, provided that the terms permit 275 | modification of the work for the customer's own use and reverse 276 | engineering for debugging such modifications. 277 | 278 | You must give prominent notice with each copy of the work that the 279 | Library is used in it and that the Library and its use are covered by 280 | this License. You must supply a copy of this License. If the work 281 | during execution displays copyright notices, you must include the 282 | copyright notice for the Library among them, as well as a reference 283 | directing the user to the copy of this License. Also, you must do one 284 | of these things: 285 | 286 | a) Accompany the work with the complete corresponding 287 | machine-readable source code for the Library including whatever 288 | changes were used in the work (which must be distributed under 289 | Sections 1 and 2 above); and, if the work is an executable linked 290 | with the Library, with the complete machine-readable "work that 291 | uses the Library", as object code and/or source code, so that the 292 | user can modify the Library and then relink to produce a modified 293 | executable containing the modified Library. (It is understood 294 | that the user who changes the contents of definitions files in the 295 | Library will not necessarily be able to recompile the application 296 | to use the modified definitions.) 297 | 298 | b) Use a suitable shared library mechanism for linking with the 299 | Library. A suitable mechanism is one that (1) uses at run time a 300 | copy of the library already present on the user's computer system, 301 | rather than copying library functions into the executable, and (2) 302 | will operate properly with a modified version of the library, if 303 | the user installs one, as long as the modified version is 304 | interface-compatible with the version that the work was made with. 305 | 306 | c) Accompany the work with a written offer, valid for at 307 | least three years, to give the same user the materials 308 | specified in Subsection 6a, above, for a charge no more 309 | than the cost of performing this distribution. 310 | 311 | d) If distribution of the work is made by offering access to copy 312 | from a designated place, offer equivalent access to copy the above 313 | specified materials from the same place. 314 | 315 | e) Verify that the user has already received a copy of these 316 | materials or that you have already sent this user a copy. 317 | 318 | For an executable, the required form of the "work that uses the 319 | Library" must include any data and utility programs needed for 320 | reproducing the executable from it. However, as a special exception, 321 | the materials to be distributed need not include anything that is 322 | normally distributed (in either source or binary form) with the major 323 | components (compiler, kernel, and so on) of the operating system on 324 | which the executable runs, unless that component itself accompanies 325 | the executable. 326 | 327 | It may happen that this requirement contradicts the license 328 | restrictions of other proprietary libraries that do not normally 329 | accompany the operating system. Such a contradiction means you cannot 330 | use both them and the Library together in an executable that you 331 | distribute. 332 | 333 | 7. You may place library facilities that are a work based on the 334 | Library side-by-side in a single library together with other library 335 | facilities not covered by this License, and distribute such a combined 336 | library, provided that the separate distribution of the work based on 337 | the Library and of the other library facilities is otherwise 338 | permitted, and provided that you do these two things: 339 | 340 | a) Accompany the combined library with a copy of the same work 341 | based on the Library, uncombined with any other library 342 | facilities. This must be distributed under the terms of the 343 | Sections above. 344 | 345 | b) Give prominent notice with the combined library of the fact 346 | that part of it is a work based on the Library, and explaining 347 | where to find the accompanying uncombined form of the same work. 348 | 349 | 8. You may not copy, modify, sublicense, link with, or distribute 350 | the Library except as expressly provided under this License. Any 351 | attempt otherwise to copy, modify, sublicense, link with, or 352 | distribute the Library is void, and will automatically terminate your 353 | rights under this License. However, parties who have received copies, 354 | or rights, from you under this License will not have their licenses 355 | terminated so long as such parties remain in full compliance. 356 | 357 | 9. You are not required to accept this License, since you have not 358 | signed it. However, nothing else grants you permission to modify or 359 | distribute the Library or its derivative works. These actions are 360 | prohibited by law if you do not accept this License. Therefore, by 361 | modifying or distributing the Library (or any work based on the 362 | Library), you indicate your acceptance of this License to do so, and 363 | all its terms and conditions for copying, distributing or modifying 364 | the Library or works based on it. 365 | 366 | 10. Each time you redistribute the Library (or any work based on the 367 | Library), the recipient automatically receives a license from the 368 | original licensor to copy, distribute, link with or modify the Library 369 | subject to these terms and conditions. You may not impose any further 370 | restrictions on the recipients' exercise of the rights granted herein. 371 | You are not responsible for enforcing compliance by third parties with 372 | this License. 373 | 374 | 11. If, as a consequence of a court judgment or allegation of patent 375 | infringement or for any other reason (not limited to patent issues), 376 | conditions are imposed on you (whether by court order, agreement or 377 | otherwise) that contradict the conditions of this License, they do not 378 | excuse you from the conditions of this License. If you cannot 379 | distribute so as to satisfy simultaneously your obligations under this 380 | License and any other pertinent obligations, then as a consequence you 381 | may not distribute the Library at all. For example, if a patent 382 | license would not permit royalty-free redistribution of the Library by 383 | all those who receive copies directly or indirectly through you, then 384 | the only way you could satisfy both it and this License would be to 385 | refrain entirely from distribution of the Library. 386 | 387 | If any portion of this section is held invalid or unenforceable under any 388 | particular circumstance, the balance of the section is intended to apply, 389 | and the section as a whole is intended to apply in other circumstances. 390 | 391 | It is not the purpose of this section to induce you to infringe any 392 | patents or other property right claims or to contest validity of any 393 | such claims; this section has the sole purpose of protecting the 394 | integrity of the free software distribution system which is 395 | implemented by public license practices. Many people have made 396 | generous contributions to the wide range of software distributed 397 | through that system in reliance on consistent application of that 398 | system; it is up to the author/donor to decide if he or she is willing 399 | to distribute software through any other system and a licensee cannot 400 | impose that choice. 401 | 402 | This section is intended to make thoroughly clear what is believed to 403 | be a consequence of the rest of this License. 404 | 405 | 12. If the distribution and/or use of the Library is restricted in 406 | certain countries either by patents or by copyrighted interfaces, the 407 | original copyright holder who places the Library under this License may add 408 | an explicit geographical distribution limitation excluding those countries, 409 | so that distribution is permitted only in or among countries not thus 410 | excluded. In such case, this License incorporates the limitation as if 411 | written in the body of this License. 412 | 413 | 13. The Free Software Foundation may publish revised and/or new 414 | versions of the Lesser General Public License from time to time. 415 | Such new versions will be similar in spirit to the present version, 416 | but may differ in detail to address new problems or concerns. 417 | 418 | Each version is given a distinguishing version number. If the Library 419 | specifies a version number of this License which applies to it and 420 | "any later version", you have the option of following the terms and 421 | conditions either of that version or of any later version published by 422 | the Free Software Foundation. If the Library does not specify a 423 | license version number, you may choose any version ever published by 424 | the Free Software Foundation. 425 | 426 | 14. If you wish to incorporate parts of the Library into other free 427 | programs whose distribution conditions are incompatible with these, 428 | write to the author to ask for permission. For software which is 429 | copyrighted by the Free Software Foundation, write to the Free 430 | Software Foundation; we sometimes make exceptions for this. Our 431 | decision will be guided by the two goals of preserving the free status 432 | of all derivatives of our free software and of promoting the sharing 433 | and reuse of software generally. 434 | 435 | NO WARRANTY 436 | 437 | 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO 438 | WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. 439 | EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR 440 | OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY 441 | KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE 442 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 443 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE 444 | LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME 445 | THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 446 | 447 | 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN 448 | WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY 449 | AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU 450 | FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR 451 | CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE 452 | LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING 453 | RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A 454 | FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF 455 | SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH 456 | DAMAGES. 457 | 458 | END OF TERMS AND CONDITIONS 459 | 460 | How to Apply These Terms to Your New Libraries 461 | 462 | If you develop a new library, and you want it to be of the greatest 463 | possible use to the public, we recommend making it free software that 464 | everyone can redistribute and change. You can do so by permitting 465 | redistribution under these terms (or, alternatively, under the terms of the 466 | ordinary General Public License). 467 | 468 | To apply these terms, attach the following notices to the library. It is 469 | safest to attach them to the start of each source file to most effectively 470 | convey the exclusion of warranty; and each file should have at least the 471 | "copyright" line and a pointer to where the full notice is found. 472 | 473 | 474 | Copyright (C) 475 | 476 | This library is free software; you can redistribute it and/or 477 | modify it under the terms of the GNU Lesser General Public 478 | License as published by the Free Software Foundation; either 479 | version 2.1 of the License, or (at your option) any later version. 480 | 481 | This library is distributed in the hope that it will be useful, 482 | but WITHOUT ANY WARRANTY; without even the implied warranty of 483 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 484 | Lesser General Public License for more details. 485 | 486 | You should have received a copy of the GNU Lesser General Public 487 | License along with this library; if not, write to the Free Software 488 | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 489 | 490 | Also add information on how to contact you by electronic and paper mail. 491 | 492 | You should also get your employer (if you work as a programmer) or your 493 | school, if any, to sign a "copyright disclaimer" for the library, if 494 | necessary. Here is a sample; alter the names: 495 | 496 | Yoyodyne, Inc., hereby disclaims all copyright interest in the 497 | library `Frob' (a library for tweaking knobs) written by James Random Hacker. 498 | 499 | , 1 April 1990 500 | Ty Coon, President of Vice 501 | 502 | That's all there is to it! -------------------------------------------------------------------------------- /README: -------------------------------------------------------------------------------- 1 | Just a simple dsl for criteria and hql with scala. 2 | 3 | Just some examples of string way: 4 | 5 | 1)session.from[User].orderBy("name".asc).orderBy("age".desc).asList[User] 6 | 7 | 2) session.from[User].where("age" >= 20).and("name" like "alberto").asList[User] 8 | 9 | 3) session.from[Address].join("user").where("user.name" equal "alberto2").asList[Address] 10 | 11 | 4) session.from[Address].join("user").where("user.name" equal "alberto2").and("user.age" >= 20).asList[Address] 12 | 13 | 5) session.query("from User where name=:name and age =:age").withParams("name" -> "alberto","age" -> alberto.getAge).asList[User] 14 | 15 | 6) session.from[User].where.hasMany("address").asList[User] 16 | 17 | Just some examples of type safe way: 18 | 19 | val user = new User 20 | val address = new Address 21 | 22 | session.from[User].orderBy(_.getName).list 23 | session.from[User].orderBy(_.getName).asc.list 24 | session.from[User].orderBy(_.getName).asc.orderBy(_.getAge).desc.list 25 | val addresses = session.from[Address].join(_.getUser).orderBy(_.getName).list 26 | val addresses = session.from[Address].join(_.getUser).where("user.name" equal "guilherme").list 27 | 28 | session.from[User].orderBy(_.getName).asc.orderBy(_.getAge).desc.asList[User] 29 | 30 | session.from[User].where(_.getAge \>= 20).where(_.getName like "alberto").asList[User] 31 | 32 | session.from[Address].join(_.getUser).where(_.getName equal "alberto2").asList[Address] 33 | 34 | session.query("from User where name=:name and age =:age").withParams("name" -> "alberto","age" -> alberto.getAge).asList[User] 35 | 36 | session.from[User].where.hasMany(_.getAddresses).asList[User] 37 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'scala' 2 | apply plugin: 'eclipse' 3 | apply plugin: 'idea' 4 | 5 | compileScala{ 6 | options.encoding='UTF-8' 7 | } 8 | 9 | compileTestScala { 10 | options.encoding='UTF-8' 11 | } 12 | 13 | repositories { 14 | mavenCentral() 15 | mavenRepo urls: 'http://repository.jboss.org/nexus/content/groups/public/' 16 | mavenRepo urls: 'http://repo1.maven.org/maven2/' 17 | mavenRepo urls: 'http://download.java.net/maven/2' 18 | mavenRepo urls: 'http://scala-tools.org/repo-releases/' 19 | } 20 | 21 | dependencies { 22 | 23 | scalaTools 'org.scala-lang:scala-compiler:2.8.1' 24 | scalaTools 'org.scala-lang:scala-library:2.8.1' 25 | 26 | 27 | compile group: 'org.scala-lang', name: 'scala-compiler', version: '2.8.1' 28 | compile group: 'org.scala-lang', name: 'scala-library', version: '2.8.1' 29 | compile group: 'org.hibernate', name: 'hibernate-core', version: '3.6.0.Beta2' 30 | compile group: 'org.slf4j', name: 'slf4j-log4j12', version: '1.6.1' 31 | compile group: 'log4j', name: 'log4j', version: '1.2.16' 32 | compile group: 'org.hibernate', name: 'hibernate-entitymanager', version: '3.6.0.Beta2', ext: 'jar' 33 | compile group: 'jboss', name: 'javassist', version: '3.1' 34 | compile group: 'cglib', name: 'cglib-nodep', version: '2.2' 35 | testCompile group: 'junit', name: 'junit', version: '4.8' 36 | testCompile group: 'org.hsqldb', name: 'hsqldb', version: '2.0.0' 37 | testCompile group: 'org.mockito', name: 'mockito-all', version: '1.8.5' 38 | lib = "$projectDir/lib" 39 | compile files(fileTree(dir: lib as File, includes: ['*.jar'])) 40 | } 41 | -------------------------------------------------------------------------------- /out/production/hibernate-query-dsl/br/com/caelum/hibernatequerydsl/ActiveCollection.scala: -------------------------------------------------------------------------------- 1 | package br.com.caelum.hibernatequerydsl 2 | 3 | import scala.collection.JavaConversions._ 4 | import net.sf.cglib.proxy.Enhancer 5 | import org.hibernate.criterion.{Criterion, Restrictions} 6 | 7 | trait Cond { 8 | def crit:Criterion 9 | } 10 | class EqCond(field:String, value:Any) extends Cond { 11 | def crit = Restrictions.eq(field, value) 12 | } 13 | 14 | class ActiveCollection[T](var elements:List[T], query:PimpedCriteria[T,T])(implicit entityType:Manifest[T]) { 15 | 16 | private type Myself = ActiveCollection[T] 17 | private def loaded = Option(elements).isDefined 18 | 19 | private implicit def listToAC(l:List[T]):Myself = new Myself(elements, null) 20 | private implicit def queryToAC(q:PimpedCriteria[T,T]):Myself = new Myself(null, q) 21 | 22 | def grabThem():List[T] = { 23 | if(!loaded) { 24 | elements = query.asList[T].toList 25 | } 26 | elements 27 | } 28 | 29 | def take(k: Int):Myself = { 30 | query.using(_.setMaxResults(k)) 31 | } 32 | 33 | def filter(f: (T) => Cond):Myself = { 34 | query.and(applyRule(f).crit) 35 | } 36 | 37 | def find(f: (T) => Cond): Option[T] = { 38 | query.and(applyRule(f).crit).using(_.setMaxResults(1)).headOption 39 | } 40 | 41 | def applyRule(f: (T) => Cond):Cond = { 42 | val handler = new ComparisonCallback 43 | val proxy = Enhancer.create(entityType.erasure, handler).asInstanceOf[T] 44 | f(proxy) 45 | } 46 | 47 | } -------------------------------------------------------------------------------- /out/production/hibernate-query-dsl/br/com/caelum/hibernatequerydsl/ComparisonCallback.scala: -------------------------------------------------------------------------------- 1 | package br.com.caelum.hibernatequerydsl 2 | 3 | import net.sf.cglib.proxy.InvocationHandler 4 | class ComparisonCallback extends InvocationHandler { 5 | 6 | def invoke(proxy:AnyRef,method:java.lang.reflect.Method,args:Array[AnyRef]) = { 7 | if(method.getReturnType!=classOf[String]) { 8 | throw new RuntimeException("We are not supporting anything but strings right now, sorry") 9 | } 10 | // TODO to implement others, we will need to use the cutest ThreadLocal ever 11 | // we can also use it with a SINGLE proxy per class by doing a list.an[User].getName 12 | 13 | // TODO switch to case or something else 14 | // TODO duplicated code, extract 15 | var _invoked = method.getName 16 | if(_invoked.startsWith("get")) { 17 | _invoked = _invoked.substring(3, _invoked.length) 18 | } else if(_invoked.startsWith("is")) { 19 | _invoked = _invoked.substring(2, _invoked.length) 20 | } 21 | val rest = if (_invoked.length() > 0) _invoked.substring(1,_invoked.length()) else "" 22 | _invoked = Character.toLowerCase(_invoked.charAt(0)) + rest 23 | _invoked 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /out/production/hibernate-query-dsl/br/com/caelum/hibernatequerydsl/Expression.scala: -------------------------------------------------------------------------------- 1 | package br.com.caelum.hibernatequerydsl 2 | 3 | import net.sf.cglib.proxy._ 4 | import java.lang.reflect.{ Method, Modifier } 5 | object Expression { 6 | val callback = () => new MethodInterceptor { 7 | implicit def string2WithRubyPowers(str: String) = new { 8 | def withFirstCharLowered = { 9 | str.substring(0, 1).toLowerCase + str.substring(1, str.length) 10 | } 11 | } 12 | 13 | val properties = scala.collection.mutable.ListBuffer[String]() 14 | def intercept(proxiedObject: Any, method: Method, params: Array[Object], methodProxy: MethodProxy) = { 15 | val GetterExpression = """(get)?(\w*){1}""".r 16 | method.getName match { 17 | case GetterExpression(_, part2) => { 18 | if (part2 != "toString") { 19 | properties += part2.withFirstCharLowered 20 | } 21 | } 22 | } 23 | if ((method.getReturnType.getModifiers & Modifier.FINAL) == 0) { 24 | proxy(method.getReturnType, this) 25 | } else { 26 | println(properties.mkString(".")) 27 | null 28 | } 29 | } 30 | } 31 | private def proxy[T](klass: Class[_], methodInterceptor: MethodInterceptor = callback()): T = { 32 | val enhancer = new Enhancer 33 | enhancer.setSuperclass(klass) 34 | enhancer.setCallback(methodInterceptor) 35 | enhancer.create.asInstanceOf[T] 36 | } 37 | def exp[T](implicit manifest: Manifest[T]): T = { 38 | proxy(manifest.erasure) 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /out/production/hibernate-query-dsl/br/com/caelum/hibernatequerydsl/InvocationMemorizingCallback.scala: -------------------------------------------------------------------------------- 1 | package br.com.caelum.hibernatequerydsl 2 | 3 | import net.sf.cglib.proxy.InvocationHandler 4 | import org.hibernate.criterion.Restrictions 5 | import java.lang.reflect.Method 6 | 7 | class InvocationMemorizingCallback extends InvocationHandler { 8 | private var _invoked: String = "" 9 | 10 | def invokedPath = _invoked 11 | 12 | def invoke(proxy: AnyRef, method: java.lang.reflect.Method, args: Array[AnyRef]) = { 13 | _invoked = method.getName 14 | // TODO switch to case or something else 15 | if (_invoked.startsWith("get")) { 16 | _invoked = _invoked.substring(3, _invoked.length) 17 | } else if (_invoked.startsWith("is")) { 18 | _invoked = _invoked.substring(2, _invoked.length) 19 | } 20 | val rest = if (_invoked.length() > 0) _invoked.substring(1, _invoked.length()) else "" 21 | _invoked = Character.toLowerCase(_invoked.charAt(0)) + rest 22 | null 23 | } 24 | } 25 | 26 | object Pimps { 27 | implicit def xxx(qq:Any) = new PimpedCriteriaCondition(target) 28 | } 29 | 30 | class PimpedCriteriaCondition(target:Any){ 31 | val proxy = target.asInstanceOf[InvocationMemorizingCallback] 32 | def \==(value:Any) = { 33 | println(proxy.invokedPath+"aaaa") 34 | Restrictions.eq(proxy.invokedPath,value) 35 | } 36 | } 37 | 38 | -------------------------------------------------------------------------------- /out/production/hibernate-query-dsl/br/com/caelum/hibernatequerydsl/OrderThis.scala: -------------------------------------------------------------------------------- 1 | package br.com.caelum.hibernatequerydsl 2 | 3 | import org.hibernate.criterion.Order 4 | 5 | // TODO if the method to construct this guy received the asc or desc as a second 6 | // parameter thourhg a import, then there would be no need for this extra guy or the 7 | // extra implicit. remove it? 8 | class OrderThis[T,P](path:String, val pimped:PimpedCriteria[T,P]) { 9 | 10 | import pimped.criteriaToPimped 11 | def asc():PimpedCriteria[T,P] = { 12 | pimped.criteria.addOrder(Order.asc(path)) 13 | } 14 | def desc():PimpedCriteria[T,P] = { 15 | pimped.criteria.addOrder(Order.desc(path)) 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /out/production/hibernate-query-dsl/br/com/caelum/hibernatequerydsl/PimpedCriteria.scala: -------------------------------------------------------------------------------- 1 | package br.com.caelum.hibernatequerydsl 2 | 3 | import org.hibernate.criterion._ 4 | import org.hibernate.criterion.Projections._ 5 | import org.hibernate.impl.CriteriaImpl 6 | import org.hibernate.transform.Transformers 7 | import org.hibernate.{Session, Criteria} 8 | import net.sf.cglib.proxy.Enhancer 9 | import scala.collection.JavaConversions._ 10 | import javax.persistence.criteria.Path 11 | 12 | /** 13 | * A criteria that will query on objects of type T, projecting 14 | * on type P. This criteria is backed by a hibernate criteria. 15 | */ 16 | class PimpedCriteria[T,P](prefix:String, val criteria: Criteria) { 17 | 18 | import PimpedSession._ 19 | type Myself = PimpedCriteria[T,P] 20 | implicit def criteriaToPimped(partial:Criteria) = new PimpedCriteria[T,P](prefix, partial) 21 | 22 | val projections = projectionList 23 | val criteriaImpl = criteria.asInstanceOf[CriteriaImpl] 24 | 25 | if (criteriaImpl.getProjection != null) { 26 | projections.add(criteriaImpl.getProjection) 27 | } 28 | 29 | def unique[Y]: Y = criteria.uniqueResult.asInstanceOf[Y] 30 | 31 | def asList[Y]: List[Y] = criteria.list.asInstanceOf[java.util.List[Y]].toList 32 | 33 | def using(f:(Criteria) => Criteria):Myself = f(criteria) 34 | 35 | def list:List[P] = asList[P] 36 | 37 | def orderBy(order: Order):Myself = criteria.addOrder(order) 38 | 39 | // TODO use only one class per entity 40 | def orderBy(f:(T) => Unit)(implicit entityType:Manifest[T]) = { 41 | val path = evaluate(f) 42 | new OrderThis[T,P](prefix + path, this) 43 | } 44 | 45 | def orderBy2[Proj](f:(Proj) => Unit)(implicit manifest:Manifest[Proj]) = { 46 | val path = evaluate(f) 47 | new OrderThis[T,Proj](path, new PimpedCriteria[T,Proj]("", criteria)) 48 | } 49 | 50 | def headOption:Option[P] = using(_.setMaxResults(1)).list.toList.asInstanceOf[List[P]].headOption 51 | 52 | def join(field: String):Myself = criteria.createAlias(field, field) 53 | 54 | def join[Joiner](f:(T) => Joiner)(implicit entityType:Manifest[T]) = { 55 | val field = evaluate(f) 56 | new PimpedCriteria[Joiner, P](prefix + field + ".", criteria.createAlias(field, field)) 57 | } 58 | 59 | private def evaluate[K,X](f:(K) => X)(implicit entityType:Manifest[K]):String = { 60 | val handler = new InvocationMemorizingCallback 61 | val proxy = Enhancer.create(entityType.erasure, handler).asInstanceOf[K] 62 | f(proxy) 63 | handler.invokedPath 64 | } 65 | 66 | def has(toManyField: String):Myself = { 67 | criteria.add(Restrictions.isNotEmpty(toManyField)) 68 | } 69 | 70 | def includes(toManyField: String):Myself = { 71 | join(toManyField).has(toManyField) 72 | } 73 | 74 | def where(condition: Criterion):Myself = { 75 | criteria.add(condition) 76 | } 77 | 78 | def where:Myself = { this } 79 | 80 | def where(f:(T) => Unit)(implicit entityType:Manifest[T]) { 81 | val field = evaluate(f) 82 | } 83 | 84 | 85 | def and(condition: Criterion):Myself = { 86 | criteria.add(condition) 87 | } 88 | 89 | def count = criteria.setProjection(rowCount).uniqueResult.asInstanceOf[Long].intValue 90 | 91 | def first[Y] = criteria.setFirstResult(0).setMaxResults(1).unique[Y] 92 | 93 | def last[Y](implicit manifest: Manifest[Y]) = { 94 | val dirtySession = criteria.asInstanceOf[CriteriaImpl].getSession.asInstanceOf[Session] 95 | val size = dirtySession.from[Y].count 96 | criteria.setFirstResult(size.intValue - 1).unique[Y] 97 | } 98 | 99 | def groupBy(fields: String*):Myself = { 100 | fields.foreach(field => { 101 | projections.add(Projections.groupProperty(field)) 102 | }) 103 | criteria.setProjection(projections) 104 | } 105 | 106 | def select(fields: String*):Myself = { 107 | fields.foreach(field => { 108 | projections.add(Projections.property(field)) 109 | }) 110 | criteria.setProjection(projections) 111 | } 112 | 113 | def selectWithAliases(fields: Projection*):Myself = { 114 | fields.foreach(projections.add(_)) 115 | criteria.setProjection(projections) 116 | } 117 | 118 | def avg(field: String):Myself = { 119 | projections.add(Projections.avg(field)) 120 | criteria.setProjection(projections) 121 | } 122 | 123 | def sum(field: String):Myself = { 124 | projections.add(Projections.sum(field)) 125 | criteria.setProjection(projections) 126 | } 127 | 128 | def count(field: String):Myself = { 129 | projections.add(Projections.count(field)) 130 | criteria.setProjection(projections) 131 | } 132 | 133 | def distinct(field:String):Myself = { 134 | projections.add(Projections.distinct(Projections.property(field))) 135 | criteria.setProjection(projections) 136 | } 137 | 138 | def transformToBean[Y](implicit manifest: Manifest[Y]) = { 139 | new Transformer[Y,P](criteria.setResultTransformer(Transformers.aliasToBean(manifest.erasure))) 140 | } 141 | } 142 | -------------------------------------------------------------------------------- /out/production/hibernate-query-dsl/br/com/caelum/hibernatequerydsl/PimpedQuery.scala: -------------------------------------------------------------------------------- 1 | package br.com.caelum.hibernatequerydsl 2 | 3 | import org.hibernate.Query 4 | import scala.collection.JavaConversions._ 5 | 6 | class PimpedQuery(query: Query) { 7 | def withParams(params: (String, Any)*) = { 8 | params.foreach((param) => { 9 | query.setParameter(param._1, param._2) 10 | }) 11 | query 12 | } 13 | 14 | def unique[T]: T = query.uniqueResult.asInstanceOf[T] 15 | 16 | def asList[T]: List[T] = query.list.asInstanceOf[java.util.List[T]].toList 17 | 18 | def headOption[T]:Option[T] = { 19 | query.setMaxResults(1).list.asInstanceOf[List[T]].headOption 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /out/production/hibernate-query-dsl/br/com/caelum/hibernatequerydsl/PimpedSession.scala: -------------------------------------------------------------------------------- 1 | package br.com.caelum.hibernatequerydsl 2 | 3 | import org.hibernate.{ Criteria, Session, Query } 4 | import org.hibernate.criterion.{ Order, Restrictions, MatchMode, Projections } 5 | import scala.reflect.{Apply, Select, Literal, Tree,Code,This } 6 | 7 | object PimpedSession { 8 | 9 | implicit def session2PimpedSession(session: Session) = new PimpedSession(session) 10 | 11 | implicit def pimpedCriteria2Criteria[T,P](pimped: PimpedCriteria[T,P]) = pimped.criteria 12 | 13 | implicit def hibernateQuery2PimpedQuery(query: Query) = new PimpedQuery(query) 14 | 15 | implicit def code2PimpedCode[T](code:Code[T]) = new PimpedCode(code) 16 | 17 | implicit def code2String[T](code:Code[T]) = new PimpedCode(code).toString 18 | 19 | implicit def orderThisToPimped[T,P](order:OrderThis[T,P]) = order.asc 20 | 21 | implicit def collectionToActive[T](elements:List[T], criteria:PimpedCriteria[T,T])(implicit t:Manifest[T]) = new ActiveCollection[T](elements, criteria) 22 | 23 | implicit def acToList[T](ac:ActiveCollection[T]) = ac.grabThem 24 | 25 | } 26 | 27 | object TypeUnsafe { 28 | implicit def string2PimpedStringCondition(field: String) = new PimpedStringCondition(field) 29 | } 30 | object TypeSafe { 31 | implicit def string2Conditioner(field: String) = new StringConditioner(field) 32 | 33 | } 34 | 35 | class PimpedCode[T](code: Code[T]) { 36 | 37 | implicit def string2WithRubyPowers(str: String) = new StringWithRubyPowers(str) 38 | 39 | class StringWithRubyPowers(str: String) { 40 | def withFirstCharLowered = { 41 | str.substring(0, 1).toLowerCase + str.substring(1, str.length) 42 | } 43 | } 44 | 45 | private def evaluate: String = { 46 | def extractString(tree: Tree, properties: List[String] = List()): List[String] = { 47 | //literal is for local variables and this for instance 48 | if (tree.isInstanceOf[Literal] ||tree.isInstanceOf[This] || tree.isInstanceOf[Select]) { 49 | return properties 50 | } 51 | 52 | val expressao = tree.asInstanceOf[Apply].fun.asInstanceOf[Select] 53 | val GetterExpression = """(get)?(\w*){1}""".r 54 | expressao.sym.name match { 55 | case GetterExpression(_, part2) => { 56 | extractString(expressao.qual, part2.withFirstCharLowered :: properties) 57 | } 58 | } 59 | } 60 | val tree = code.tree 61 | extractString(tree).mkString(".") 62 | } 63 | 64 | override def toString = evaluate 65 | 66 | def equal(value: Any) = Restrictions.eq(evaluate, value) 67 | 68 | def >(value: Any) = Restrictions.gt(evaluate, value) 69 | 70 | def >=(value: Any) = Restrictions.ge(evaluate, value) 71 | 72 | def <(value: Any) = Restrictions.lt(evaluate, value) 73 | 74 | def <=(value: Any) = Restrictions.le(evaluate, value) 75 | 76 | def !==(value: Any) = Restrictions.ne(evaluate,value) 77 | 78 | def like(value: String) = Restrictions.ilike(evaluate, value, MatchMode.ANYWHERE) 79 | 80 | def isNull = Restrictions.isNull(evaluate) 81 | 82 | def isNotNull = Restrictions.isNotNull(evaluate) 83 | 84 | def desc = Order.desc(evaluate) 85 | 86 | def asc = Order.asc(evaluate) 87 | 88 | def alias(newName: String) = Projections.property(evaluate).as(newName) 89 | } 90 | 91 | 92 | class PimpedStringCondition(field: String) { 93 | def equal(value: Any) = Restrictions.eq(field, value) 94 | 95 | def >(value: Any) = Restrictions.gt(field, value) 96 | 97 | def >=(value: Any) = Restrictions.ge(field, value) 98 | 99 | def <(value: Any) = Restrictions.lt(field, value) 100 | 101 | def <=(value: Any) = Restrictions.le(field, value) 102 | 103 | def !==(value: Any) = Restrictions.ne(field,value) 104 | 105 | def like(value: String) = Restrictions.ilike(field, value, MatchMode.ANYWHERE) 106 | 107 | def isNull = Restrictions.isNull(field) 108 | 109 | def isNotNull = Restrictions.isNotNull(field) 110 | 111 | def desc = Order.desc(field) 112 | 113 | def asc = Order.asc(field) 114 | 115 | def alias(newName: String) = Projections.property(field).as(newName) 116 | 117 | } 118 | 119 | class StringConditioner(field: String) { 120 | def equal(value: Any) = new EqCond(field, value) 121 | } 122 | 123 | class PimpedSession(session: Session) { 124 | 125 | def all[T](implicit manifest:Manifest[T]) = { 126 | from[T].list 127 | } 128 | 129 | def from[T](implicit manifest: Manifest[T]) = { 130 | val criteria = session.createCriteria(manifest.erasure) 131 | new PimpedCriteria[T,T]("", criteria) 132 | } 133 | 134 | def query(query: String) = session.createQuery(query) 135 | 136 | def count[T](implicit manifest: Manifest[T]) = from[T].count 137 | 138 | def exists[T](implicit manifest: Manifest[T]) = count[T] > 0 139 | 140 | def first[T](implicit manifest: Manifest[T]) = from[T].first[T] 141 | 142 | def last[T](implicit manifest: Manifest[T]) = from[T].last[T] 143 | } 144 | 145 | 146 | class Transformer[T,P](criteria: Criteria) { 147 | def asList = new PimpedCriteria[T,P]("", criteria).asList[T] 148 | 149 | def unique = new PimpedCriteria[T,P]("", criteria).unique[T] 150 | } 151 | 152 | -------------------------------------------------------------------------------- /out/test/hibernate-query-dsl/br/com/caelum/hibernatequerydsl/ActiveCollectionAcceptanceTest.scala: -------------------------------------------------------------------------------- 1 | package br.com.caelum.hibernatequerydsl 2 | 3 | import org.hibernate.Session 4 | import org.hibernate.cfg.Configuration 5 | import org.junit.{Test, After, Before} 6 | import org.junit.Assert._ 7 | import br.com.caelum.hibernatequerydsl.PimpedSession._ 8 | import br.com.caelum.hibernatequerydsl.TypeSafe._ 9 | class ActiveCollectionAcceptanceTest { 10 | 11 | private var session:Session = _ 12 | 13 | @Before 14 | def setUp { 15 | val cfg = new Configuration(); 16 | session = cfg.configure().buildSessionFactory().openSession(); 17 | session.beginTransaction(); 18 | } 19 | 20 | @After 21 | def tearDown{ 22 | if (session != null && session.getTransaction().isActive()) { 23 | session.getTransaction().rollback(); 24 | } 25 | } 26 | 27 | private def withUser(name:String=null,age:Int=0, street:String=null) = { 28 | val user = new User 29 | user setName name 30 | user setAge age 31 | session.save(user) 32 | if(street!=null){ 33 | val address = new Address 34 | address setStreet street 35 | address setUser user 36 | session.save(address) 37 | } 38 | this 39 | } 40 | 41 | private def and(name:String=null,age:Int=0, street:String=null) = { 42 | withUser(name, age, street) 43 | } 44 | 45 | def ar = new ActiveCollection[User](null, session.from[User]) 46 | 47 | @Test 48 | def shouldSupportTake { 49 | withUser("guilherme").and("alberto") 50 | val users = ar.take(1) 51 | assertEquals("guilherme", users(0).getName) 52 | assertEquals(1, users.size) 53 | } 54 | 55 | @Test 56 | def shouldSupportParametersCombinedWithTake { 57 | withUser("guilherme").and("alberto") 58 | val users = ar.filter(_.getName equal "alberto").take(1) 59 | assertEquals("alberto", users(0).getName) 60 | assertEquals(1, users.size) 61 | } 62 | 63 | @Test 64 | def shouldSupportGrabbingAll { 65 | withUser("guilherme").and("alberto") 66 | val users:List[User] = ar 67 | assertEquals(2, users.size) 68 | } 69 | 70 | @Test 71 | def shouldSupportRegrabbing { 72 | withUser("guilherme").and("alberto") 73 | val users = ar 74 | assertEquals(2, users.size) 75 | assertEquals(classOf[ActiveCollection[User]], ar.getClass) 76 | assertEquals(1, users.take(1).size) 77 | } 78 | 79 | } -------------------------------------------------------------------------------- /out/test/hibernate-query-dsl/br/com/caelum/hibernatequerydsl/PimpedSessionTest.scala: -------------------------------------------------------------------------------- 1 | package br.com.caelum.hibernatequerydsl 2 | 3 | import org.junit.Ignore 4 | import scala.reflect.BeanProperty 5 | import org.hibernate.cfg.Configuration 6 | import br.com.caelum.hibernatequerydsl.PimpedSession._ 7 | import br.com.caelum.hibernatequerydsl.Expression._ 8 | import org.hibernate.Session 9 | import org.hibernate.criterion.Order._ 10 | import org.junit.{ Test, Before, After } 11 | import org.junit.Assert._ 12 | import scala.reflect.Code._ 13 | import br.com.caelum.hibernatequerydsl.TypeUnsafe._ 14 | 15 | class PimpedClassTest { 16 | 17 | private var session: Session = _ 18 | private val userToQuery = new User 19 | private val addressToQuery = new Address 20 | 21 | @Before 22 | def setUp { 23 | val cfg = new Configuration(); 24 | //cfg.configure().setProperty("hibernate.connection.url", "jdbc:hsqldb:mem:mydvdsDB"); 25 | session = cfg.configure().buildSessionFactory().openSession(); 26 | session.beginTransaction(); 27 | } 28 | 29 | /** 30 | * Undoing all changes to database 31 | * @throws Exception 32 | */ 33 | @After 34 | def tearDown { 35 | if (session != null && session.getTransaction().isActive()) { 36 | session.getTransaction().rollback(); 37 | } 38 | } 39 | 40 | private def newUser(name: String = null, age: Int = 0) = { 41 | val user = new User 42 | user setName name 43 | user setAge age 44 | session.save(user) 45 | user 46 | } 47 | 48 | private def newAddress(street: String, user: User) = { 49 | val address = new Address 50 | address setStreet street 51 | address setUser user 52 | session.save(address) 53 | address 54 | } 55 | 56 | @Test 57 | def shouldListAllObjects { 58 | newUser("alberto") 59 | newUser("alberto") 60 | val users = session.all[User] 61 | assertEquals(2, users size) 62 | } 63 | 64 | @Test 65 | def shouldVerifyIfExists { 66 | newUser("alberto") 67 | assertTrue(session.exists[User]) 68 | } 69 | 70 | @Test 71 | def shouldVerifyIfNotExists { 72 | assertFalse(session.exists[User]) 73 | } 74 | 75 | @Test 76 | def shouldCount { 77 | newUser("alberto") 78 | newUser("alberto") 79 | assertEquals(2, session.count[User]) 80 | } 81 | 82 | @Test 83 | def shouldGetFirstBasedOnId { 84 | val alberto = newUser("alberto") 85 | newUser("alberto2") 86 | val userRetrieved = session.first[User] 87 | assertEquals(alberto, userRetrieved) 88 | } 89 | 90 | @Test 91 | def shouldGetFirstBasedOnSomeField { 92 | val alberto = newUser("alberto") 93 | val joao = newUser("joao") 94 | val userRetrieved = session.from[User].orderBy(_.getName).desc.first[User] 95 | assertEquals(joao, userRetrieved) 96 | } 97 | 98 | @Test 99 | def shouldGetTheLastBasedOnId { 100 | val alberto = newUser("alberto") 101 | val joao = newUser("joao") 102 | val userRetrieved = session.last[User] 103 | assertEquals(joao, userRetrieved) 104 | } 105 | 106 | @Test 107 | def shouldGetTheLastDescOrderedOnSomeField { 108 | val alberto = newUser("alberto") 109 | val joao = newUser("joao") 110 | val userRetrieved = session.from[User].orderBy(_.getName).desc.last[User] 111 | assertEquals(alberto, userRetrieved) 112 | } 113 | 114 | @Test 115 | def shouldGetTheLastDescOrderedOnSomeFields { 116 | val alberto = newUser("alberto") 117 | val joao = newUser("joao") 118 | val userRetrieved = session.from[User].orderBy(_.getName).desc.last[User] 119 | assertEquals(alberto, userRetrieved) 120 | } 121 | 122 | @Test 123 | def shouldGetTheLastAscOrderedOnSomeField { 124 | val alberto = newUser("alberto") 125 | val joao = newUser("joao") 126 | val userRetrieved = session.from[User].orderBy(_.getName).asc.last[User] 127 | assertEquals(joao, userRetrieved) 128 | } 129 | 130 | @Test 131 | def shouldGetTheLastAscAndDescOrderedOnSomeFields { 132 | val alberto = newUser("alberto", 10) 133 | val alberto2 = newUser("alberto", 20) 134 | val userRetrieved = session.from[User].orderBy(_.getName).asc.orderBy(_.getAge).desc.last[User] 135 | assertEquals(alberto, userRetrieved) 136 | } 137 | 138 | @Test 139 | def shouldDoASimpleJoin { 140 | val alberto = newUser("alberto") 141 | val address = newAddress("rua da casa de nao sei quem", alberto) 142 | val address2 = newAddress("rua da casa de nao sei quem", alberto) 143 | val list = session.from[Address].join(_.getUser).asList[Address] 144 | assertEquals(2, list size) 145 | 146 | } 147 | 148 | @Test 149 | def shouldDoASimpleJoinBasedOnSomeField1 { 150 | val alberto = newUser("alberto") 151 | val alberto2 = newUser("alberto2") 152 | val address = newAddress("rua da casa de nao sei quem", alberto) 153 | val address2 = newAddress("rua da casa de nao sei quem", alberto2) 154 | //pimpedCondition(_.getName).\==("alberto2") 155 | val list = session.from[Address].join(_.getUser).where(_.getName.\==("alberto2")).asList[Address] 156 | assertEquals(1, list size) 157 | 158 | } 159 | 160 | @Test 161 | def shouldDoASimpleJoinBasedOnSomeFieldsWithAnd { 162 | val alberto = newUser("alberto", 10) 163 | val alberto2 = newUser("alberto2", 20) 164 | val address = newAddress("rua da casa de nao sei quem", alberto) 165 | val address2 = newAddress("rua da casa de nao sei quem", alberto2) 166 | val list = session.from[Address].join(_.getUser).where(lift(addressToQuery.getUser.getName).equal("alberto2")).and(lift(addressToQuery.getUser.getAge).equal(alberto2.getAge)).asList[Address] 167 | assertEquals(1, list size) 168 | } 169 | 170 | @Test 171 | def shouldDoASimpleQueryBasedOnSomeFields1 { 172 | val alberto = newUser("alberto", 10) 173 | val alberto2 = newUser("alberto2", 20) 174 | val alberto3 = newUser("alberto3", 30) 175 | val alberto4 = newUser("alberto4", 40) 176 | val list = session.from[User].where(lift(userToQuery.getAge) > alberto.getAge).asList[User] 177 | assertEquals(3, list size) 178 | } 179 | 180 | @Test 181 | def shouldDoASimpleQueryBasedOnSomeFields2 { 182 | val alberto = newUser("alberto", 10) 183 | val alberto2 = newUser("alberto2", 20) 184 | val alberto3 = newUser("alberto3", 30) 185 | val alberto4 = newUser("alberto4", 40) 186 | var list = session.from[User].where(lift(userToQuery.getAge) >= alberto.getAge).asList[User] 187 | assertEquals(4, list size) 188 | } 189 | 190 | @Test 191 | def shouldDoASimpleQueryBasedOnSomeFields3 { 192 | val alberto = newUser("alberto", 10) 193 | val alberto2 = newUser("alberto2", 20) 194 | val alberto3 = newUser("alberto3", 30) 195 | val alberto4 = newUser("alberto4", 40) 196 | val list = session.from[User].where(lift(userToQuery.getAge) < alberto2.getAge).asList[User] 197 | assertEquals(1, list size) 198 | } 199 | 200 | @Test 201 | def shouldDoASimpleQueryBasedOnSomeFields4 { 202 | val alberto = newUser("alberto", 10) 203 | val alberto2 = newUser("alberto2", 20) 204 | val alberto3 = newUser("alberto3", 30) 205 | val alberto4 = newUser("alberto4", 40) 206 | val list = session.from[User].where(lift(userToQuery.getAge) <= alberto2.getAge).asList[User] 207 | assertEquals(2, list size) 208 | } 209 | 210 | @Test 211 | def shouldDoASimpleQueryBasedOnSomeFields5 { 212 | val alberto = newUser("alberto", 10) 213 | val alberto2 = newUser("alberto2", 20) 214 | val alberto3 = newUser("alberto3", 30) 215 | val alberto4 = newUser("outrute", 40) 216 | val list = session.from[User].where(lift(userToQuery.getAge) >= alberto2.getAge).and(lift(userToQuery.getName) like "alberto").asList[User] 217 | assertEquals(2, list size) 218 | } 219 | 220 | @Test 221 | def shouldDoASimpleQueryBasedOnSomeFields6 { 222 | val alberto = newUser(null, 10) 223 | val alberto2 = newUser("alberto2", 20) 224 | val alberto3 = newUser("alberto3", 30) 225 | val alberto4 = newUser("outrute", 40) 226 | val list = session.from[User].where(lift(userToQuery.getName) isNull).asList[User] 227 | assertEquals(1, list size) 228 | } 229 | 230 | @Test 231 | def shouldDoASimpleQueryBasedOnSomeFields7 { 232 | val alberto = newUser(null, 10) 233 | val alberto2 = newUser("alberto2", 20) 234 | val alberto3 = newUser("alberto3", 30) 235 | val alberto4 = newUser("outrute", 40) 236 | val list = session.from[User].where(lift(userToQuery.getName) isNotNull).asList[User] 237 | assertEquals(3, list size) 238 | } 239 | 240 | @Test 241 | def shouldDoASimpleQueryBasedOnSomeFields8 { 242 | val alberto = newUser("alberto", 10) 243 | val alberto2 = newUser("alberto2", 20) 244 | val alberto3 = newUser("alberto3", 30) 245 | val alberto4 = newUser("alberto4", 40) 246 | val list = session.from[User].where("name" !== "alberto").asList[User] 247 | assertEquals(3, list size) 248 | } 249 | 250 | @Test 251 | def shouldExecuteJustASimpleHQL { 252 | val alberto = newUser("alberto", 10) 253 | val alberto2 = newUser("alberto2", 20) 254 | val alberto3 = newUser("alberto3", 30) 255 | val alberto4 = newUser("outrute", 40) 256 | val list = session.query("from User").asList[User] 257 | assertEquals(4, list size) 258 | } 259 | 260 | @Test 261 | def shouldAssingParametersForHQL { 262 | val alberto = newUser("alberto", 10) 263 | val alberto2 = newUser("alberto2", 20) 264 | val alberto3 = newUser("alberto3", 30) 265 | val alberto4 = newUser("outrute", 40) 266 | val list = session.query("from User where name=:name and age =:age").withParams("name" -> "alberto", "age" -> alberto.getAge).asList[User] 267 | assertEquals(1, list size) 268 | } 269 | 270 | @Test 271 | def shouldGroupUserByStreet { 272 | val alberto = newUser("alberto", 10) 273 | val alberto2 = newUser("alberto2", 20) 274 | val alberto3 = newUser("alberto3", 15) 275 | val alberto4 = newUser("alberto4", 30) 276 | val address = newAddress("x", alberto) 277 | val address2 = newAddress("x", alberto2) 278 | val address3 = newAddress("y", alberto3) 279 | val address4 = newAddress("y", alberto4) 280 | val list = session.from[User].join(lift(userToQuery.getAddresses)).groupBy("addresses.street").asList[User] 281 | assertEquals(2, list size) 282 | } 283 | 284 | @Test 285 | def shouldGroupUserByStreetWithAvgAge { 286 | val alberto = newUser("alberto", 10) 287 | val alberto2 = newUser("alberto2", 20) 288 | val alberto3 = newUser("alberto3", 15) 289 | val alberto4 = newUser("alberto4", 30) 290 | val address = newAddress("x", alberto) 291 | val address2 = newAddress("x", alberto2) 292 | val address3 = newAddress("y", alberto3) 293 | val address4 = newAddress("y", alberto4) 294 | val list = session.from[User].join(lift(userToQuery.getAddresses)).groupBy("addresses.street").avg(lift(userToQuery.getAge)).asList[Array[Object]] 295 | assertEquals(2, list size) 296 | assertEquals(15.0, list.head(1)) 297 | } 298 | 299 | @Test 300 | def shouldGroupUserByStreetWithSumAge { 301 | val alberto = newUser("alberto", 10) 302 | val alberto2 = newUser("alberto2", 20) 303 | val alberto3 = newUser("alberto3", 15) 304 | val alberto4 = newUser("alberto4", 30) 305 | val address = newAddress("x", alberto) 306 | val address2 = newAddress("x", alberto2) 307 | val address3 = newAddress("y", alberto3) 308 | val address4 = newAddress("y", alberto4) 309 | val list = session.from[User].join(lift(userToQuery.getAddresses)).groupBy("addresses.street").sum(lift(userToQuery.getAge)).asList[Array[Object]] 310 | assertEquals(2, list size) 311 | assertEquals(30L, list.head(1)) 312 | } 313 | 314 | @Test 315 | def shouldGroupUserByStreetWithCountAge { 316 | val alberto = newUser("alberto", 10) 317 | val alberto2 = newUser("alberto2", 20) 318 | val alberto3 = newUser("alberto3", 15) 319 | val alberto4 = newUser("alberto4", 30) 320 | val address = newAddress("x", alberto) 321 | val address2 = newAddress("x", alberto2) 322 | val address3 = newAddress("y", alberto3) 323 | val address4 = newAddress("y", alberto4) 324 | val list = session.from[User].join(lift(userToQuery.getAddresses)).groupBy("addresses.street").count(lift(userToQuery.getAge)).asList[Array[Object]] 325 | assertEquals(2, list size) 326 | assertEquals(2L, list.head(1)) 327 | } 328 | 329 | @Test 330 | def shouldListJustUsersWithAddresses { 331 | val alberto = newUser("alberto", 10) 332 | val alberto2 = newUser("alberto2", 20) 333 | val alberto3 = newUser("alberto3", 15) 334 | val alberto4 = newUser("alberto4", 30) 335 | val address = newAddress("x", alberto) 336 | val address2 = newAddress("x", alberto2) 337 | val address3 = newAddress("y", alberto3) 338 | 339 | val list = session.from[User].where.has(lift(userToQuery.getAddresses)).asList[User] 340 | assertEquals(3, list size) 341 | } 342 | 343 | @Test 344 | def shouldListJustUsersWithAddressesFilteringBySomeAttribute { 345 | val alberto = newUser("alberto", 10) 346 | val alberto2 = newUser("alberto2", 20) 347 | val alberto3 = newUser("alberto3", 15) 348 | val alberto4 = newUser("alberto4", 30) 349 | val address = newAddress("x", alberto) 350 | val address2 = newAddress("x", alberto2) 351 | val address3 = newAddress("y", alberto3) 352 | 353 | val list = session.from[User].includes(lift(userToQuery.getAddresses)).where("addresses.street" equal "y").asList[User] 354 | assertEquals(1, list size) 355 | } 356 | 357 | @Test 358 | def shouldListJustUsersWithAddressesFilteringBySomeAttribute2 { 359 | val alberto = newUser("alberto", 10) 360 | val alberto2 = newUser("alberto2", 20) 361 | val alberto3 = newUser("alberto3", 15) 362 | val alberto4 = newUser("alberto4", 30) 363 | val address = newAddress("x", alberto) 364 | val address2 = newAddress("x", alberto2) 365 | val address3 = newAddress("y", alberto3) 366 | val list = session.from[User].includes(lift(userToQuery.getAddresses)).where("addresses.street" equal "y").asList[User] 367 | assertEquals(1, list size) 368 | } 369 | 370 | @Test 371 | def shouldSelectByFields { 372 | val alberto = newUser("alberto", 10) 373 | val alberto2 = newUser("alberto2", 20) 374 | val alberto3 = newUser("alberto3", 15) 375 | val alberto4 = newUser("alberto4", 30) 376 | val address = newAddress("x", alberto) 377 | val address2 = newAddress("x", alberto2) 378 | val address3 = newAddress("y", alberto3) 379 | val list = session.from[User].select(lift(userToQuery.getName)).asList[String] 380 | assertEquals("alberto", list.head) 381 | } 382 | 383 | @Test 384 | def shouldSelectDistinctedObjects { 385 | val alberto = newUser("alberto", 10) 386 | val alberto2 = newUser("alberto", 20) 387 | val alberto3 = newUser("alberto", 15) 388 | val alberto4 = newUser("alberto4", 30) 389 | val list = session.from[User].distinct("name").asList[String] 390 | assertEquals(2, list.size) 391 | } 392 | 393 | @Ignore //TODO fazer o resulttransformer funcionar. 394 | def shouldTransformArrayToMyResultTransformer { 395 | val alberto = newUser("alberto", 10) 396 | val alberto2 = newUser("alberto2", 20) 397 | val alberto3 = newUser("alberto3", 15) 398 | 399 | val alberto4 = newUser("alberto4", 30) 400 | val address = newAddress("x", alberto) 401 | val address2 = newAddress("x", alberto2) 402 | val address3 = newAddress("y", alberto3) 403 | val list = session.from[User].join(lift(userToQuery.getAddresses)).select(lift(userToQuery.getName)).selectWithAliases("addresses.street".alias("street")).transformToBean[StreetWithName].asList 404 | assertEquals("alberto", list.head.getName) 405 | } 406 | } 407 | -------------------------------------------------------------------------------- /out/test/hibernate-query-dsl/br/com/caelum/hibernatequerydsl/TestingTest.scala: -------------------------------------------------------------------------------- 1 | package br.com.caelum.hibernatequerydsl 2 | 3 | import net.sf.cglib.proxy.Enhancer 4 | 5 | object TestingTest { 6 | def main(args: Array[String]): Unit = { 7 | import br.com.caelum.hibernatequerydsl.Pimps._ 8 | val handler = new InvocationMemorizingCallback 9 | 10 | val proxy = Enhancer.create(classOf[User], handler).asInstanceOf[User] 11 | println(proxy.getName.\==("alberto")) 12 | } 13 | } 14 | 15 | -------------------------------------------------------------------------------- /out/test/hibernate-query-dsl/br/com/caelum/hibernatequerydsl/TypeSafeAcceptanceTest.scala: -------------------------------------------------------------------------------- 1 | package br.com.caelum.hibernatequerydsl 2 | 3 | import org.hibernate.Session 4 | import org.hibernate.cfg.Configuration 5 | import org.junit.{Test, After, Before} 6 | import org.junit.Assert._ 7 | import br.com.caelum.hibernatequerydsl.PimpedSession._ 8 | import br.com.caelum.hibernatequerydsl.TypeUnsafe._ 9 | class TypeSafeAcceptanceTest { 10 | 11 | private var session:Session = _ 12 | 13 | @Before 14 | def setUp { 15 | val cfg = new Configuration(); 16 | session = cfg.configure().buildSessionFactory().openSession(); 17 | session.beginTransaction(); 18 | } 19 | 20 | @After 21 | def tearDown{ 22 | if (session != null && session.getTransaction().isActive()) { 23 | session.getTransaction().rollback(); 24 | } 25 | } 26 | 27 | private def withUser(name:String=null,age:Int=0, street:String=null) = { 28 | val user = new User 29 | user setName name 30 | user setAge age 31 | session.save(user) 32 | if(street!=null){ 33 | val address = new Address 34 | address setStreet street 35 | address setUser user 36 | session.save(address) 37 | } 38 | this 39 | } 40 | 41 | private def and(name:String=null,age:Int=0, street:String=null) = { 42 | withUser(name, age, street) 43 | } 44 | 45 | @Test 46 | def shouldListAllObjects { 47 | withUser("guilherme").and("alberto") 48 | val users = session.from[User].orderBy(_.getName).asc.list 49 | assertEquals("alberto", users.head.getName) 50 | assertEquals("guilherme", users(1).getName) 51 | } 52 | 53 | 54 | @Test 55 | def shouldSupportComingBackToCriteriaAndAgainToPimped { 56 | withUser("guilherme").and("alberto") 57 | val users = session.from[User].orderBy(_.getName).asc.using(_.setMaxResults(1)).list 58 | assertEquals("alberto", users.head.getName) 59 | assertEquals(1, users.size) 60 | } 61 | 62 | @Test 63 | def shouldSupportOrderingByTwoElements { 64 | withUser("guilherme", 16).and("guilherme", 20) 65 | val users = session.from[User].orderBy(_.getName).asc.orderBy(_.getAge).desc.list 66 | assertEquals(20, users.head.getAge) 67 | assertEquals(16, users(1).getAge) 68 | } 69 | 70 | @Test 71 | def shouldSupportTypeSafeJoining { 72 | withUser("guilherme", 29, "street 1").and("alberto", 26, "street 2") 73 | val addresses = session.from[Address].join(_.getUser).where("user.name" equal "guilherme").list 74 | assertEquals(29, addresses.head.getUser.getAge) 75 | assertEquals(1, addresses.size) 76 | } 77 | 78 | 79 | @Test 80 | def shouldSupportJoiningAndProjectingOnTheBaseObject { 81 | withUser("guilherme", 29, "street 1").and("alberto", 26, "street 2") 82 | val addresses = session.from[Address].join(_.getUser).orderBy(_.getName).list 83 | assertEquals("alberto", addresses.head.getUser.getName) 84 | } 85 | 86 | @Test 87 | def shouldSupportComingBackFromTheOtherGuys { 88 | withUser("guilherme", 29, "Vergueiro").and("guilherme", 26, "Paulista") 89 | val addresses = session.from[Address].join(_.getUser).where("user.name" equal "guilherme").orderBy2[Address](_.getStreet).asc.list 90 | assertEquals(26, addresses.head.getUser.getAge) 91 | } 92 | 93 | } -------------------------------------------------------------------------------- /out/test/hibernate-query-dsl/hibernate.cfg.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 8 | 9 | org.hibernate.dialect.HSQLDialect 10 | jdbc:hsqldb:mem:mydvdsDB 11 | org.hsqldb.jdbcDriver 12 | sa 13 | 14 | 15 | true 16 | true 17 | update 18 | org.hibernate.cache.HashtableCacheProvider 19 | 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /src/main/scala/br/com/caelum/hibernatequerydsl/ActiveCollection.scala: -------------------------------------------------------------------------------- 1 | package br.com.caelum.hibernatequerydsl 2 | 3 | import scala.collection.JavaConversions._ 4 | import net.sf.cglib.proxy.Enhancer 5 | import org.hibernate.criterion.{Criterion, Restrictions} 6 | 7 | trait Cond { 8 | def crit:Criterion 9 | } 10 | class EqCond(field:String, value:Any) extends Cond { 11 | def crit = Restrictions.eq(field, value) 12 | } 13 | 14 | class ActiveCollection[T](var elements:List[T], query:PimpedCriteria[T,T])(implicit entityType:Manifest[T]) { 15 | 16 | private type Myself = ActiveCollection[T] 17 | private type Condition = (T) => Cond 18 | private def loaded = Option(elements).isDefined 19 | 20 | private implicit def listToAC(l:List[T]):Myself = new Myself(elements, null) 21 | private implicit def queryToAC(q:PimpedCriteria[T,T]):Myself = new Myself(null, q) 22 | 23 | def grabThem():List[T] = { 24 | if(!loaded) { 25 | elements = query.asList[T].toList 26 | } 27 | elements 28 | } 29 | 30 | def take(k: Int):Myself = { 31 | query.using(_.setMaxResults(k)) 32 | } 33 | 34 | def drop(k:Int): Myself = { 35 | query.using(_.setFirstResult(k)) 36 | } 37 | 38 | def dropWhile(f:(T) => Boolean) = { 39 | grabThem.dropWhile(f) 40 | } 41 | 42 | def exists(f: Condition):Boolean = { 43 | find(f).isDefined 44 | } 45 | 46 | def filter(f: Condition):Myself = { 47 | query.and(applyRule(f).crit) 48 | } 49 | 50 | def find(f: Condition): Option[T] = { 51 | query.and(applyRule(f).crit).using(_.setMaxResults(1)).headOption 52 | } 53 | 54 | def applyRule(f: Condition):Cond = { 55 | val handler = new ComparisonCallback 56 | val proxy = Enhancer.create(entityType.erasure, handler).asInstanceOf[T] 57 | f(proxy) 58 | } 59 | 60 | } -------------------------------------------------------------------------------- /src/main/scala/br/com/caelum/hibernatequerydsl/ComparisonCallback.scala: -------------------------------------------------------------------------------- 1 | package br.com.caelum.hibernatequerydsl 2 | 3 | import net.sf.cglib.proxy.InvocationHandler 4 | class ComparisonCallback extends InvocationHandler { 5 | 6 | def invoke(proxy:AnyRef,method:java.lang.reflect.Method,args:Array[AnyRef]) = { 7 | if(method.getReturnType!=classOf[String]) { 8 | throw new RuntimeException("We are not supporting anything but strings right now, sorry") 9 | } 10 | // TODO to implement others, we will need to use the cutest ThreadLocal ever 11 | // we can also use it with a SINGLE proxy per class by doing a list.an[User].getName 12 | 13 | // TODO switch to case or something else 14 | // TODO duplicated code, extract 15 | var _invoked = method.getName 16 | if(_invoked.startsWith("get")) { 17 | _invoked = _invoked.substring(3, _invoked.length) 18 | } else if(_invoked.startsWith("is")) { 19 | _invoked = _invoked.substring(2, _invoked.length) 20 | } 21 | val rest = if (_invoked.length() > 0) _invoked.substring(1,_invoked.length()) else "" 22 | _invoked = Character.toLowerCase(_invoked.charAt(0)) + rest 23 | _invoked 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/main/scala/br/com/caelum/hibernatequerydsl/Expression.scala: -------------------------------------------------------------------------------- 1 | package br.com.caelum.hibernatequerydsl 2 | 3 | import net.sf.cglib.proxy._ 4 | import java.lang.reflect.{ Method, Modifier } 5 | object Expression { 6 | val callback = () => new MethodInterceptor { 7 | implicit def string2WithRubyPowers(str: String) = new { 8 | def withFirstCharLowered = { 9 | str.substring(0, 1).toLowerCase + str.substring(1, str.length) 10 | } 11 | } 12 | 13 | val properties = scala.collection.mutable.ListBuffer[String]() 14 | def intercept(proxiedObject: Any, method: Method, params: Array[Object], methodProxy: MethodProxy) = { 15 | val GetterExpression = """(get)?(\w*){1}""".r 16 | method.getName match { 17 | case GetterExpression(_, part2) => { 18 | if (part2 != "toString") { 19 | properties += part2.withFirstCharLowered 20 | } 21 | } 22 | } 23 | if ((method.getReturnType.getModifiers & Modifier.FINAL) == 0) { 24 | proxy(method.getReturnType, this) 25 | } else { 26 | println(properties.mkString(".")) 27 | null 28 | } 29 | } 30 | } 31 | private def proxy[T](klass: Class[_], methodInterceptor: MethodInterceptor = callback()): T = { 32 | val enhancer = new Enhancer 33 | enhancer.setSuperclass(klass) 34 | enhancer.setCallback(methodInterceptor) 35 | enhancer.create.asInstanceOf[T] 36 | } 37 | def exp[T](implicit manifest: Manifest[T]): T = { 38 | proxy(manifest.erasure) 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/scala/br/com/caelum/hibernatequerydsl/InvocationMemorizingCallback.scala: -------------------------------------------------------------------------------- 1 | package br.com.caelum.hibernatequerydsl 2 | 3 | import net.sf.cglib.proxy.InvocationHandler 4 | import java.lang.reflect.Method 5 | import java.lang.{ThreadLocal, Boolean} 6 | import org.hibernate.criterion.{Projections, Order, MatchMode, Restrictions} 7 | 8 | object Pig{ 9 | val tl = new ThreadLocal[InvocationMemorizingCallback] 10 | } 11 | 12 | class StringWithRubyPowers(str: String) { 13 | def withFirstCharLowered = { 14 | str.substring(0, 1).toLowerCase + str.substring(1, str.length) 15 | } 16 | } 17 | 18 | 19 | class InvocationMemorizingCallback(val prefix:String = "") extends InvocationHandler { 20 | 21 | Pig.tl.set(this) 22 | 23 | implicit def string2WithRubyPowers(str: String) = new StringWithRubyPowers(str) 24 | private var _invoked: String = "" 25 | var properties = List[String]() 26 | 27 | def invokedPath = properties.mkString(".") 28 | 29 | def invoke(proxy: AnyRef, method: java.lang.reflect.Method, args: Array[AnyRef]) = { 30 | _invoked = method.getName 31 | val GetterExpression = """(get|is)?(\w*){1}""".r 32 | _invoked match { 33 | case GetterExpression(_, part2) => { 34 | properties = part2.withFirstCharLowered :: properties 35 | } 36 | } 37 | //a little "mangue". I tried to test instanceOf[java.lang.Boolean] and scala.Boolean and the return was false... 38 | if(method.getReturnType.getName.eq("boolean")) new Boolean("false") else null 39 | } 40 | } 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /src/main/scala/br/com/caelum/hibernatequerydsl/OrderThis.scala: -------------------------------------------------------------------------------- 1 | package br.com.caelum.hibernatequerydsl 2 | 3 | import org.hibernate.criterion.Order 4 | 5 | // TODO if the method to construct this guy received the asc or desc as a second 6 | // parameter thourhg a import, then there would be no need for this extra guy or the 7 | // extra implicit. remove it? 8 | class OrderThis[T,P](path:String, val pimped:PimpedCriteria[T,P]) { 9 | 10 | import pimped.criteriaToPimped 11 | def asc():PimpedCriteria[T,P] = { 12 | pimped.criteria.addOrder(Order.asc(path)) 13 | } 14 | def desc():PimpedCriteria[T,P] = { 15 | pimped.criteria.addOrder(Order.desc(path)) 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/main/scala/br/com/caelum/hibernatequerydsl/PimpedCriteria.scala: -------------------------------------------------------------------------------- 1 | package br.com.caelum.hibernatequerydsl 2 | 3 | import org.hibernate.criterion._ 4 | import org.hibernate.criterion.Projections._ 5 | import org.hibernate.impl.CriteriaImpl 6 | import org.hibernate.transform.Transformers 7 | import org.hibernate.{ Session, Criteria } 8 | import net.sf.cglib.proxy.Enhancer 9 | import scala.collection.JavaConversions._ 10 | 11 | /** 12 | * A criteria that will query on objects of type T, projecting 13 | * on type P. This criteria is backed by a hibernate criteria. 14 | */ 15 | class PimpedCriteria[T, P](prefix: String, val criteria: Criteria) { 16 | 17 | import PimpedSession._ 18 | type Myself = PimpedCriteria[T, P] 19 | implicit def criteriaToPimped(partial: Criteria) = new PimpedCriteria[T, P](prefix, partial) 20 | 21 | val projections = projectionList 22 | val criteriaImpl = criteria.asInstanceOf[CriteriaImpl] 23 | 24 | if (criteriaImpl.getProjection != null) { 25 | projections.add(criteriaImpl.getProjection) 26 | } 27 | 28 | def unique[Y]: Y = criteria.uniqueResult.asInstanceOf[Y] 29 | 30 | def asList[Y]: List[Y] = criteria.list.asInstanceOf[java.util.List[Y]].toList 31 | 32 | def using(f: (Criteria) => Criteria): Myself = f(criteria) 33 | 34 | def list: List[P] = asList[P] 35 | 36 | def orderBy(order: Order): Myself = criteria.addOrder(order) 37 | 38 | // TODO use only one class per entity 39 | def orderBy(f: (T) => Unit)(implicit entityType: Manifest[T]) = { 40 | val path = evaluate(f).invokedPath 41 | new OrderThis[T, P](prefix + path, this) 42 | } 43 | 44 | def orderBy2[Proj](f: (Proj) => Unit)(implicit manifest: Manifest[Proj]) = { 45 | val path = evaluate(f).invokedPath 46 | new OrderThis[T, Proj](path, new PimpedCriteria[T, Proj]("", criteria)) 47 | } 48 | 49 | def headOption: Option[P] = using(_.setMaxResults(1)).list.toList.asInstanceOf[List[P]].headOption 50 | 51 | def join(field: String): Myself = criteria.createAlias(field, field) 52 | 53 | def join[Joiner](f: (T) => Joiner)(implicit entityType: Manifest[T]) = { 54 | val field = evaluate(f).invokedPath 55 | new PimpedCriteria[Joiner, P](prefix + field + ".", criteria.createAlias(field, field)) 56 | } 57 | 58 | private def evaluate[K, X](f: (K) => X)(implicit entityType: Manifest[K]): InvocationMemorizingCallback = { 59 | val handler = new InvocationMemorizingCallback 60 | val proxy = Enhancer.create(entityType.erasure, handler).asInstanceOf[K] 61 | f(proxy) 62 | handler 63 | } 64 | 65 | def has(toManyField: String): Myself = { 66 | criteria.add(Restrictions.isNotEmpty(toManyField)) 67 | } 68 | 69 | def has(f: (T) => Unit)(implicit entityType: Manifest[T]): Myself = { 70 | criteria.add(Restrictions.isNotEmpty(evaluate(f).invokedPath)) 71 | } 72 | 73 | def includes(toManyField: String): Myself = { 74 | join(toManyField).has(toManyField) 75 | } 76 | 77 | def includes(f: (T) => Unit)(implicit entityType: Manifest[T]): Myself = { 78 | val field = evaluate(f).invokedPath 79 | join(field).has(field) 80 | } 81 | 82 | def where(condition: Criterion): Myself = { 83 | criteria.add(condition) 84 | } 85 | 86 | def where: Myself = { this } 87 | 88 | def where(f: (T) => Criterion)(implicit entityType: Manifest[T]): Myself = { 89 | val handler = new InvocationMemorizingCallback(prefix) 90 | val proxy = Enhancer.create(entityType.erasure, handler).asInstanceOf[T] 91 | val condition = f(proxy) 92 | //println(condition) 93 | criteria.add(condition) 94 | } 95 | 96 | def and(condition: Criterion): Myself = { 97 | criteria.add(condition) 98 | } 99 | 100 | def count = criteria.setProjection(rowCount).uniqueResult.asInstanceOf[Long].intValue 101 | 102 | def first[Y] = criteria.setFirstResult(0).setMaxResults(1).unique[Y] 103 | 104 | def last[Y](implicit manifest: Manifest[Y]) = { 105 | val dirtySession = criteria.asInstanceOf[CriteriaImpl].getSession.asInstanceOf[Session] 106 | val size = dirtySession.from[Y].count 107 | criteria.setFirstResult(size.intValue - 1).unique[Y] 108 | } 109 | 110 | def groupBy(fields: String*): Myself = { 111 | fields.foreach(field => { 112 | projections.add(Projections.groupProperty(field)) 113 | }) 114 | criteria.setProjection(projections) 115 | } 116 | 117 | def select(fields: String*): Myself = { 118 | fields.foreach(field => { 119 | projections.add(Projections.property(field)) 120 | }) 121 | criteria.setProjection(projections) 122 | } 123 | 124 | def selectWithAliases(fields: Projection*): Myself = { 125 | fields.foreach(projections.add(_)) 126 | criteria.setProjection(projections) 127 | } 128 | 129 | def avg(field: String): Myself = { 130 | projections.add(Projections.avg(field)) 131 | criteria.setProjection(projections) 132 | } 133 | 134 | def avg[Proj](f: (Proj) => Unit)(implicit entityType: Manifest[Proj]): Myself = { 135 | avg(evaluate(f).invokedPath) 136 | } 137 | 138 | def sum(field: String): Myself = { 139 | projections.add(Projections.sum(field)) 140 | criteria.setProjection(projections) 141 | } 142 | 143 | def sum[Proj](f: (Proj) => Unit)(implicit entityType: Manifest[Proj]): Myself = { 144 | sum(evaluate(f).invokedPath) 145 | } 146 | 147 | def count(field: String): Myself = { 148 | projections.add(Projections.count(field)) 149 | criteria.setProjection(projections) 150 | } 151 | 152 | def count[Proj](f: (Proj) => Unit)(implicit entityType: Manifest[Proj]): Myself = { 153 | count(evaluate(f).invokedPath) 154 | } 155 | 156 | def distinct(field: String): Myself = { 157 | projections.add(Projections.distinct(Projections.property(field))) 158 | criteria.setProjection(projections) 159 | } 160 | 161 | def distinct2[Proj](f: (Proj) => Unit)(implicit entityType: Manifest[Proj]): Myself = { 162 | distinct(evaluate(f).invokedPath) 163 | } 164 | 165 | def distinct(f: (T) => Unit)(implicit entityType: Manifest[T]): Myself = { 166 | distinct(evaluate(f).invokedPath) 167 | } 168 | 169 | 170 | 171 | def transformToBean[Y](implicit manifest: Manifest[Y]) = { 172 | new Transformer[Y, P](criteria.setResultTransformer(Transformers.aliasToBean(manifest.erasure))) 173 | } 174 | } 175 | -------------------------------------------------------------------------------- /src/main/scala/br/com/caelum/hibernatequerydsl/PimpedQuery.scala: -------------------------------------------------------------------------------- 1 | package br.com.caelum.hibernatequerydsl 2 | 3 | import org.hibernate.Query 4 | import scala.collection.JavaConversions._ 5 | 6 | class PimpedQuery(query: Query) { 7 | def withParams(params: (String, Any)*) = { 8 | params.foreach((param) => { 9 | query.setParameter(param._1, param._2) 10 | }) 11 | query 12 | } 13 | 14 | def unique[T]: T = query.uniqueResult.asInstanceOf[T] 15 | 16 | def asList[T]: List[T] = query.list.asInstanceOf[java.util.List[T]].toList 17 | 18 | def headOption[T]:Option[T] = { 19 | query.setMaxResults(1) 20 | asList[T].headOption 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/scala/br/com/caelum/hibernatequerydsl/PimpedSession.scala: -------------------------------------------------------------------------------- 1 | package br.com.caelum.hibernatequerydsl 2 | 3 | import org.hibernate.{Criteria, Session, Query} 4 | import org.hibernate.criterion.{Order, Restrictions, MatchMode, Projections} 5 | 6 | import java.io.Serializable 7 | 8 | object PimpedSession { 9 | 10 | implicit def session2PimpedSession(session: Session) = new PimpedSession(session) 11 | 12 | implicit def pimpedCriteria2Criteria[T, P](pimped: PimpedCriteria[T, P]) = pimped.criteria 13 | 14 | implicit def hibernateQuery2PimpedQuery(query: Query) = new PimpedQuery(query) 15 | 16 | implicit def orderThisToPimped[T, P](order: OrderThis[T, P]) = order.asc 17 | 18 | implicit def collectionToActive[T](elements: List[T], criteria: PimpedCriteria[T, T])(implicit t: Manifest[T]) = new ActiveCollection[T](elements, criteria) 19 | 20 | implicit def acToList[T](ac: ActiveCollection[T]) = ac.grabThem 21 | 22 | } 23 | 24 | object TypeUnsafe { 25 | implicit def string2PimpedStringCondition(field: String) = new PimpedStringCondition(field) 26 | } 27 | 28 | object TypeSafe { 29 | implicit def string2Conditioner(field: String) = new StringConditioner(field) 30 | } 31 | 32 | object TypeSafeCondition { 33 | implicit def anything2TypeSafeCondition(qq: Any) = new TypeSafeCriteriaCondition(Pig.tl.get) 34 | } 35 | 36 | class TypeSafeCriteriaCondition(proxy: InvocationMemorizingCallback) { 37 | 38 | val field = proxy.prefix + proxy.invokedPath 39 | 40 | def \==(value: Any) = Restrictions.eq(field, value) 41 | 42 | def \>(value: Any) = Restrictions.gt(field, value) 43 | 44 | def \>=(value: Any) = Restrictions.ge(field, value) 45 | 46 | def \<(value: Any) = Restrictions.lt(field, value) 47 | 48 | def \<=(value: Any) = Restrictions.le(field, value) 49 | 50 | def \!=(value: Any) = Restrictions.ne(field, value) 51 | 52 | def like(value: String) = Restrictions.ilike(field, value, MatchMode.ANYWHERE) 53 | 54 | def isNull = Restrictions.isNull(field) 55 | 56 | def isNotNull = Restrictions.isNotNull(field) 57 | 58 | def alias(newName: String) = Projections.property(field).as(newName) 59 | } 60 | 61 | 62 | class PimpedStringCondition(field: String) { 63 | def equal(value: Any) = Restrictions.eq(field, value) 64 | 65 | def >(value: Any) = Restrictions.gt(field, value) 66 | 67 | def >=(value: Any) = Restrictions.ge(field, value) 68 | 69 | def <(value: Any) = Restrictions.lt(field, value) 70 | 71 | def <=(value: Any) = Restrictions.le(field, value) 72 | 73 | def !==(value: Any) = Restrictions.ne(field, value) 74 | 75 | def like(value: String) = Restrictions.ilike(field, value, MatchMode.ANYWHERE) 76 | 77 | def isNull = Restrictions.isNull(field) 78 | 79 | def isNotNull = Restrictions.isNotNull(field) 80 | 81 | def desc = Order.desc(field) 82 | 83 | def asc = Order.asc(field) 84 | 85 | def alias(newName: String) = Projections.property(field).as(newName) 86 | 87 | } 88 | 89 | class StringConditioner(field: String) { 90 | def equal(value: Any) = new EqCond(field, value) 91 | } 92 | 93 | class PimpedSession(session: Session) { 94 | 95 | def all[T](implicit manifest: Manifest[T]) = { 96 | from[T].list 97 | } 98 | 99 | def from[T](implicit manifest: Manifest[T]) = { 100 | val criteria = session.createCriteria(manifest.erasure) 101 | new PimpedCriteria[T, T]("", criteria) 102 | } 103 | 104 | def query(query: String) = session.createQuery(query) 105 | 106 | def count[T](implicit manifest: Manifest[T]) = from[T].count 107 | 108 | def exists[T](implicit manifest: Manifest[T]) = count[T] > 0 109 | 110 | def first[T](implicit manifest: Manifest[T]) = from[T].first[T] 111 | 112 | def last[T](implicit manifest: Manifest[T]) = from[T].last[T] 113 | 114 | def load[T](implicit manifest: Manifest[T], id: Serializable) = { 115 | session.load(manifest.erasure, id).asInstanceOf[T] 116 | } 117 | 118 | } 119 | 120 | 121 | 122 | -------------------------------------------------------------------------------- /src/main/scala/br/com/caelum/hibernatequerydsl/Transformer.scala: -------------------------------------------------------------------------------- 1 | package br.com.caelum.hibernatequerydsl 2 | 3 | import org.hibernate.Criteria 4 | 5 | class Transformer[T,P](criteria: Criteria) { 6 | def asList = new PimpedCriteria[T,P]("", criteria).asList[T] 7 | 8 | def unique = new PimpedCriteria[T,P]("", criteria).unique[T] 9 | } 10 | -------------------------------------------------------------------------------- /src/test/resources/hibernate.cfg.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 8 | 9 | org.hibernate.dialect.HSQLDialect 10 | jdbc:hsqldb:mem:mydvdsDB 11 | org.hsqldb.jdbcDriver 12 | sa 13 | 14 | 15 | true 16 | true 17 | update 18 | org.hibernate.cache.HashtableCacheProvider 19 | 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /src/test/scala/br/com/caelum/hibernatequerydsl/ActiveCollectionAcceptanceTest.scala: -------------------------------------------------------------------------------- 1 | package br.com.caelum.hibernatequerydsl 2 | 3 | import org.hibernate.Session 4 | import org.hibernate.cfg.Configuration 5 | import org.junit.{Test, After, Before} 6 | import org.junit.Assert._ 7 | import br.com.caelum.hibernatequerydsl.PimpedSession._ 8 | import br.com.caelum.hibernatequerydsl.TypeSafe._ 9 | class ActiveCollectionAcceptanceTest { 10 | 11 | private var session:Session = _ 12 | 13 | @Before 14 | def setUp { 15 | val cfg = new Configuration(); 16 | session = cfg.configure().buildSessionFactory().openSession(); 17 | session.beginTransaction(); 18 | } 19 | 20 | @After 21 | def tearDown{ 22 | if (session != null && session.getTransaction().isActive()) { 23 | session.getTransaction().rollback(); 24 | } 25 | } 26 | 27 | private def withUser(name:String=null,age:Int=0, street:String=null) = { 28 | val user = new User 29 | user setName name 30 | user setAge age 31 | session.save(user) 32 | if(street!=null){ 33 | val address = new Address 34 | address setStreet street 35 | address setUser user 36 | session.save(address) 37 | } 38 | this 39 | } 40 | 41 | private def and(name:String=null,age:Int=0, street:String=null) = { 42 | withUser(name, age, street) 43 | } 44 | 45 | def ar = new ActiveCollection[User](null, session.from[User]) 46 | 47 | @Test 48 | def shouldSupportTake { 49 | withUser("guilherme").and("alberto") 50 | val users = ar.take(1) 51 | assertEquals("guilherme", users(0).getName) 52 | assertEquals(1, users.size) 53 | } 54 | 55 | @Test 56 | def shouldSupportParametersCombinedWithTake { 57 | withUser("guilherme").and("alberto") 58 | val users = ar.filter(_.getName equal "alberto").take(1) 59 | assertEquals("alberto", users(0).getName) 60 | assertEquals(1, users.size) 61 | } 62 | 63 | 64 | @Test 65 | def shouldSupportFindingAnElement { 66 | withUser("guilherme", 29).and("alberto").and("guilherme", 30) 67 | val users = ar.find(_.getName equal "guilherme") 68 | assertEquals(29, users.get.getAge) 69 | } 70 | 71 | @Test 72 | def shouldSupportDroppingSomething { 73 | withUser("guilherme", 29).and("alberto").and("guilherme", 30) 74 | val users = ar.filter(_.getName equal "guilherme").drop(1) 75 | assertEquals(30, users.head.getAge) 76 | } 77 | 78 | 79 | 80 | @Test 81 | def shouldSupportCheckingIfAnElementExists { 82 | withUser("guilherme").and("alberto") 83 | assertTrue(ar.exists(_.getName equal "alberto")) 84 | assertFalse(ar.exists(_.getName equal "marcos")) 85 | } 86 | 87 | @Test 88 | def shouldSupportGrabbingAll { 89 | withUser("guilherme").and("alberto") 90 | val users:List[User] = ar 91 | assertEquals(2, users.size) 92 | } 93 | 94 | @Test 95 | def shouldSupportRegrabbing { 96 | withUser("guilherme").and("alberto") 97 | val users = ar 98 | assertEquals(2, users.size) 99 | assertEquals(classOf[ActiveCollection[User]], ar.getClass) 100 | assertEquals(1, users.take(1).size) 101 | } 102 | 103 | } -------------------------------------------------------------------------------- /src/test/scala/br/com/caelum/hibernatequerydsl/Address.java: -------------------------------------------------------------------------------- 1 | package br.com.caelum.hibernatequerydsl; 2 | 3 | import javax.persistence.Entity; 4 | import javax.persistence.GeneratedValue; 5 | import javax.persistence.Id; 6 | import javax.persistence.ManyToOne; 7 | 8 | import org.hibernate.criterion.Projections; 9 | 10 | @Entity 11 | public class Address { 12 | 13 | @Id 14 | @GeneratedValue 15 | private Integer id; 16 | private String street; 17 | @ManyToOne 18 | private User user; 19 | 20 | public Integer getId() { 21 | return id; 22 | } 23 | 24 | public void setId(Integer id) { 25 | this.id = id; 26 | } 27 | 28 | public String getStreet() { 29 | return street; 30 | } 31 | 32 | public void setStreet(String street) { 33 | this.street = street; 34 | } 35 | 36 | public User getUser() { 37 | return user; 38 | } 39 | 40 | public void setUser(User user) { 41 | this.user = user; 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /src/test/scala/br/com/caelum/hibernatequerydsl/PimpedSessionTest.scala: -------------------------------------------------------------------------------- 1 | package br.com.caelum.hibernatequerydsl 2 | 3 | import org.junit.Ignore 4 | import scala.reflect.BeanProperty 5 | import org.hibernate.cfg.Configuration 6 | import br.com.caelum.hibernatequerydsl.PimpedSession._ 7 | import br.com.caelum.hibernatequerydsl.Expression._ 8 | import org.hibernate.Session 9 | import org.hibernate.criterion.Order._ 10 | import org.junit.{ Test, Before, After } 11 | import org.junit.Assert._ 12 | import br.com.caelum.hibernatequerydsl.TypeSafeCondition._ 13 | 14 | class PimpedClassTest { 15 | 16 | private var session: Session = _ 17 | private val userToQuery = new User 18 | private val addressToQuery = new Address 19 | 20 | @Before 21 | def setUp { 22 | val cfg = new Configuration(); 23 | //cfg.configure().setProperty("hibernate.connection.url", "jdbc:hsqldb:mem:mydvdsDB"); 24 | session = cfg.configure().buildSessionFactory().openSession(); 25 | session.beginTransaction(); 26 | } 27 | 28 | /** 29 | * Undoing all changes to database 30 | * @throws Exception 31 | */ 32 | @After 33 | def tearDown { 34 | if (session != null && session.getTransaction().isActive()) { 35 | session.getTransaction().rollback(); 36 | } 37 | } 38 | 39 | private def newUser(name: String = null, age: Int = 0) = { 40 | val user = new User 41 | user setName name 42 | user setAge age 43 | session.save(user) 44 | user 45 | } 46 | 47 | private def newAddress(street: String, user: User) = { 48 | val address = new Address 49 | address setStreet street 50 | address setUser user 51 | session.save(address) 52 | address 53 | } 54 | 55 | @Test 56 | def shouldListAllObjects { 57 | newUser("alberto") 58 | newUser("alberto") 59 | val users = session.all[User] 60 | assertEquals(2, users size) 61 | } 62 | 63 | @Test 64 | def shouldVerifyIfExists { 65 | newUser("alberto") 66 | assertTrue(session.exists[User]) 67 | } 68 | 69 | @Test 70 | def shouldVerifyIfNotExists { 71 | assertFalse(session.exists[User]) 72 | } 73 | 74 | @Test 75 | def shouldCount { 76 | newUser("alberto") 77 | newUser("alberto") 78 | assertEquals(2, session.count[User]) 79 | } 80 | 81 | @Test 82 | def shouldGetFirstBasedOnId { 83 | val alberto = newUser("alberto") 84 | newUser("alberto2") 85 | val userRetrieved = session.first[User] 86 | assertEquals(alberto, userRetrieved) 87 | } 88 | 89 | @Test 90 | def shouldGetFirstBasedOnSomeField { 91 | val alberto = newUser("alberto") 92 | val joao = newUser("joao") 93 | val userRetrieved = session.from[User].orderBy(_.getName).desc.first[User] 94 | assertEquals(joao, userRetrieved) 95 | } 96 | 97 | @Test 98 | def shouldGetTheLastBasedOnId { 99 | val alberto = newUser("alberto") 100 | val joao = newUser("joao") 101 | val userRetrieved = session.last[User] 102 | assertEquals(joao, userRetrieved) 103 | } 104 | 105 | @Test 106 | def shouldGetTheLastDescOrderedOnSomeField { 107 | val alberto = newUser("alberto") 108 | val joao = newUser("joao") 109 | val userRetrieved = session.from[User].orderBy(_.getName).desc.last[User] 110 | assertEquals(alberto, userRetrieved) 111 | } 112 | 113 | @Test 114 | def shouldGetTheLastDescOrderedOnSomeFields { 115 | val alberto = newUser("alberto") 116 | val joao = newUser("joao") 117 | val userRetrieved = session.from[User].orderBy(_.getName).desc.last[User] 118 | assertEquals(alberto, userRetrieved) 119 | } 120 | 121 | @Test 122 | def shouldGetTheLastAscOrderedOnSomeField { 123 | val alberto = newUser("alberto") 124 | val joao = newUser("joao") 125 | val userRetrieved = session.from[User].orderBy(_.getName).asc.last[User] 126 | assertEquals(joao, userRetrieved) 127 | } 128 | 129 | @Test 130 | def shouldGetTheLastAscAndDescOrderedOnSomeFields { 131 | val alberto = newUser("alberto", 10) 132 | val alberto2 = newUser("alberto", 20) 133 | val userRetrieved = session.from[User].orderBy(_.getName).asc.orderBy(_.getAge).desc.last[User] 134 | assertEquals(alberto, userRetrieved) 135 | } 136 | 137 | @Test 138 | def shouldDoASimpleJoin { 139 | val alberto = newUser("alberto") 140 | val address = newAddress("rua da casa de nao sei quem", alberto) 141 | val address2 = newAddress("rua da casa de nao sei quem", alberto) 142 | val list = session.from[Address].join(_.getUser).asList[Address] 143 | assertEquals(2, list size) 144 | 145 | } 146 | 147 | @Test 148 | def shouldDoASimpleJoinBasedOnSomeField1 { 149 | val alberto = newUser("alberto") 150 | val alberto2 = newUser("alberto2") 151 | val address = newAddress("rua da casa de nao sei quem", alberto) 152 | val address2 = newAddress("rua da casa de nao sei quem", alberto2) 153 | //pimpedCondition(_.getName).\==("alberto2") 154 | val list = session.from[Address].join(_.getUser).where(_.getName.\==("alberto2")).asList[Address] 155 | assertEquals(1, list size) 156 | 157 | } 158 | 159 | @Test 160 | def shouldDoASimpleJoinBasedOnSomeFieldsWithAnd { 161 | val alberto = newUser("alberto", 10) 162 | val alberto2 = newUser("alberto2", 20) 163 | val address = newAddress("rua da casa de nao sei quem", alberto) 164 | val address2 = newAddress("rua da casa de nao sei quem", alberto2) 165 | val list = session.from[Address].join(_.getUser).where(_.getName \== ("alberto2")).where(_.getAge \== alberto2.getAge).asList[Address] 166 | assertEquals(1, list size) 167 | } 168 | 169 | @Test 170 | def shouldDoASimpleQueryBasedOnSomeFields1 { 171 | val alberto = newUser("alberto", 10) 172 | val alberto2 = newUser("alberto2", 20) 173 | val alberto3 = newUser("alberto3", 30) 174 | val alberto4 = newUser("alberto4", 40) 175 | val list = session.from[User].where(_.getAge \> alberto.getAge).asList[User] 176 | assertEquals(3, list size) 177 | } 178 | 179 | @Test 180 | def shouldDoASimpleQueryBasedOnSomeFields2 { 181 | val alberto = newUser("alberto", 10) 182 | val alberto2 = newUser("alberto2", 20) 183 | val alberto3 = newUser("alberto3", 30) 184 | val alberto4 = newUser("alberto4", 40) 185 | var list = session.from[User].where(_.getAge \>= alberto.getAge).asList[User] 186 | assertEquals(4, list size) 187 | } 188 | 189 | @Test 190 | def shouldDoASimpleQueryBasedOnSomeFields3 { 191 | val alberto = newUser("alberto", 10) 192 | val alberto2 = newUser("alberto2", 20) 193 | val alberto3 = newUser("alberto3", 30) 194 | val alberto4 = newUser("alberto4", 40) 195 | val list = session.from[User].where(_.getAge \< alberto2.getAge).asList[User] 196 | assertEquals(1, list size) 197 | } 198 | 199 | @Test 200 | def shouldDoASimpleQueryBasedOnSomeFields4 { 201 | val alberto = newUser("alberto", 10) 202 | val alberto2 = newUser("alberto2", 20) 203 | val alberto3 = newUser("alberto3", 30) 204 | val alberto4 = newUser("alberto4", 40) 205 | val list = session.from[User].where(_.getAge \<= alberto2.getAge).asList[User] 206 | assertEquals(2, list size) 207 | } 208 | 209 | @Test 210 | def shouldDoASimpleQueryBasedOnSomeFields5 { 211 | val alberto = newUser("alberto", 10) 212 | val alberto2 = newUser("alberto2", 20) 213 | val alberto3 = newUser("alberto3", 30) 214 | val alberto4 = newUser("outrute", 40) 215 | val list = session.from[User].where(_.getAge \>= alberto2.getAge).where(_.getName like "alberto").asList[User] 216 | assertEquals(2, list size) 217 | } 218 | 219 | @Test 220 | def shouldDoASimpleQueryBasedOnSomeFields6 { 221 | val alberto = newUser(null, 10) 222 | val alberto2 = newUser("alberto2", 20) 223 | val alberto3 = newUser("alberto3", 30) 224 | val alberto4 = newUser("outrute", 40) 225 | val list = session.from[User].where(_.getName isNull).asList[User] 226 | assertEquals(1, list size) 227 | } 228 | 229 | @Test 230 | def shouldDoASimpleQueryBasedOnSomeFields7 { 231 | val alberto = newUser(null, 10) 232 | val alberto2 = newUser("alberto2", 20) 233 | val alberto3 = newUser("alberto3", 30) 234 | val alberto4 = newUser("outrute", 40) 235 | val list = session.from[User].where(_.getName isNotNull).asList[User] 236 | assertEquals(3, list size) 237 | } 238 | 239 | @Test 240 | def shouldDoASimpleQueryBasedOnSomeFields8 { 241 | val alberto = newUser("alberto", 10) 242 | val alberto2 = newUser("alberto2", 20) 243 | val alberto3 = newUser("alberto3", 30) 244 | val alberto4 = newUser("alberto4", 40) 245 | val list = session.from[User].where(_.getName \!= "alberto").asList[User] 246 | assertEquals(3, list size) 247 | } 248 | 249 | @Test 250 | def shouldExecuteJustASimpleHQL { 251 | val alberto = newUser("alberto", 10) 252 | val alberto2 = newUser("alberto2", 20) 253 | val alberto3 = newUser("alberto3", 30) 254 | val alberto4 = newUser("outrute", 40) 255 | val list = session.query("from User").asList[User] 256 | assertEquals(4, list size) 257 | } 258 | 259 | @Test 260 | def shouldAssingParametersForHQL { 261 | val alberto = newUser("alberto", 10) 262 | val alberto2 = newUser("alberto2", 20) 263 | val alberto3 = newUser("alberto3", 30) 264 | val alberto4 = newUser("outrute", 40) 265 | val list = session.query("from User where name=:name and age =:age").withParams("name" -> "alberto", "age" -> alberto.getAge).asList[User] 266 | assertEquals(1, list size) 267 | } 268 | 269 | @Test 270 | def shouldGroupUserByStreet { 271 | val alberto = newUser("alberto", 10) 272 | val alberto2 = newUser("alberto2", 20) 273 | val alberto3 = newUser("alberto3", 15) 274 | val alberto4 = newUser("alberto4", 30) 275 | val address = newAddress("x", alberto) 276 | val address2 = newAddress("x", alberto2) 277 | val address3 = newAddress("y", alberto3) 278 | val address4 = newAddress("y", alberto4) 279 | val list = session.from[User].join(_.getAddresses).groupBy("addresses.street").asList[User] 280 | assertEquals(2, list size) 281 | } 282 | 283 | @Test 284 | def shouldGroupUserByStreetWithAvgAge { 285 | val alberto = newUser("alberto", 10) 286 | val alberto2 = newUser("alberto2", 20) 287 | val alberto3 = newUser("alberto3", 15) 288 | val alberto4 = newUser("alberto4", 30) 289 | val address = newAddress("x", alberto) 290 | val address2 = newAddress("x", alberto2) 291 | val address3 = newAddress("y", alberto3) 292 | val address4 = newAddress("y", alberto4) 293 | val list = session.from[User].join(_.getAddresses).groupBy("addresses.street").avg[User](_.getAge).asList[Array[Object]] 294 | assertEquals(2, list size) 295 | assertEquals(15.0, list.head(1)) 296 | } 297 | 298 | @Test 299 | def shouldGroupUserByStreetWithSumAge { 300 | val alberto = newUser("alberto", 10) 301 | val alberto2 = newUser("alberto2", 20) 302 | val alberto3 = newUser("alberto3", 15) 303 | val alberto4 = newUser("alberto4", 30) 304 | val address = newAddress("x", alberto) 305 | val address2 = newAddress("x", alberto2) 306 | val address3 = newAddress("y", alberto3) 307 | val address4 = newAddress("y", alberto4) 308 | val list = session.from[User].join(_.getAddresses).groupBy("addresses.street").sum[User](_.getAge).asList[Array[Object]] 309 | assertEquals(2, list size) 310 | assertEquals(30L, list.head(1)) 311 | } 312 | 313 | @Test 314 | def shouldGroupUserByStreetWithCountAge { 315 | val alberto = newUser("alberto", 10) 316 | val alberto2 = newUser("alberto2", 20) 317 | val alberto3 = newUser("alberto3", 15) 318 | val alberto4 = newUser("alberto4", 30) 319 | val address = newAddress("x", alberto) 320 | val address2 = newAddress("x", alberto2) 321 | val address3 = newAddress("y", alberto3) 322 | val address4 = newAddress("y", alberto4) 323 | val list = session.from[User].join(_.getAddresses).groupBy("addresses.street").count[User](_.getAge).asList[Array[Object]] 324 | assertEquals(2, list size) 325 | assertEquals(2L, list.head(1)) 326 | } 327 | 328 | @Test 329 | def shouldListJustUsersWithAddresses { 330 | val alberto = newUser("alberto", 10) 331 | val alberto2 = newUser("alberto2", 20) 332 | val alberto3 = newUser("alberto3", 15) 333 | val alberto4 = newUser("alberto4", 30) 334 | val address = newAddress("x", alberto) 335 | val address2 = newAddress("x", alberto2) 336 | val address3 = newAddress("y", alberto3) 337 | 338 | val list = session.from[User].where.has(_.getAddresses).asList[User] 339 | assertEquals(3, list size) 340 | } 341 | 342 | @Test 343 | def shouldListJustUsersWithAddressesFilteringBySomeAttribute { 344 | val alberto = newUser("alberto", 10) 345 | val alberto2 = newUser("alberto2", 20) 346 | val alberto3 = newUser("alberto3", 15) 347 | val alberto4 = newUser("alberto4", 30) 348 | val address = newAddress("x", alberto) 349 | val address2 = newAddress("x", alberto2) 350 | val address3 = newAddress("y", alberto3) 351 | import br.com.caelum.hibernatequerydsl.TypeUnsafe._ 352 | val list = session.from[User].includes(_.getAddresses).where("addresses.street" equal "y").asList[User] 353 | assertEquals(1, list size) 354 | } 355 | 356 | @Test 357 | def shouldListJustUsersWithAddressesFilteringBySomeAttribute2 { 358 | val alberto = newUser("alberto", 10) 359 | val alberto2 = newUser("alberto2", 20) 360 | val alberto3 = newUser("alberto3", 15) 361 | val alberto4 = newUser("alberto4", 30) 362 | val address = newAddress("x", alberto) 363 | val address2 = newAddress("x", alberto2) 364 | val address3 = newAddress("y", alberto3) 365 | import br.com.caelum.hibernatequerydsl.TypeUnsafe._ 366 | val list = session.from[User].includes(_.getAddresses).where("addresses.street" equal "y").asList[User] 367 | assertEquals(1, list size) 368 | } 369 | 370 | @Test 371 | def shouldSelectByFields { 372 | val alberto = newUser("alberto", 10) 373 | val alberto2 = newUser("alberto2", 20) 374 | val alberto3 = newUser("alberto3", 15) 375 | val alberto4 = newUser("alberto4", 30) 376 | val address = newAddress("x", alberto) 377 | val address2 = newAddress("x", alberto2) 378 | val address3 = newAddress("y", alberto3) 379 | val list = session.from[User].select("name").asList[String] 380 | assertEquals("alberto", list.head) 381 | } 382 | 383 | @Test 384 | def shouldSelectDistinctedObjects { 385 | val alberto = newUser("alberto", 10) 386 | val alberto2 = newUser("alberto", 20) 387 | val alberto3 = newUser("alberto", 15) 388 | val alberto4 = newUser("alberto4", 30) 389 | val list = session.from[User].distinct(_.getName).asList[String] 390 | assertEquals(2, list.size) 391 | } 392 | 393 | @Ignore //TODO fazer o resulttransformer funcionar. 394 | def shouldTransformArrayToMyResultTransformer { 395 | val alberto = newUser("alberto", 10) 396 | val alberto2 = newUser("alberto2", 20) 397 | val alberto3 = newUser("alberto3", 15) 398 | 399 | val alberto4 = newUser("alberto4", 30) 400 | val address = newAddress("x", alberto) 401 | val address2 = newAddress("x", alberto2) 402 | val address3 = newAddress("y", alberto3) 403 | val list = session.from[User].join(_.getAddresses).select("name").selectWithAliases("addresses.street".alias("street")).transformToBean[StreetWithName].asList 404 | assertEquals("alberto", list.head.getName) 405 | } 406 | } 407 | -------------------------------------------------------------------------------- /src/test/scala/br/com/caelum/hibernatequerydsl/StreetWithName.java: -------------------------------------------------------------------------------- 1 | package br.com.caelum.hibernatequerydsl; 2 | 3 | 4 | public class StreetWithName { 5 | 6 | private String street; 7 | private String name; 8 | 9 | public String getStreet() { 10 | return street; 11 | } 12 | 13 | public void setStreet(String street) { 14 | this.street = street; 15 | } 16 | 17 | public String getName() { 18 | return name; 19 | } 20 | 21 | public void setName(String name) { 22 | this.name = name; 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/test/scala/br/com/caelum/hibernatequerydsl/TestingTest.scala: -------------------------------------------------------------------------------- 1 | package br.com.caelum.hibernatequerydsl 2 | 3 | import net.sf.cglib.proxy.Enhancer 4 | 5 | object TestingTest { 6 | def main(args: Array[String]): Unit = { 7 | var handler = new InvocationMemorizingCallback 8 | 9 | var proxy = Enhancer.create(classOf[User], handler).asInstanceOf[User] 10 | } 11 | } 12 | 13 | -------------------------------------------------------------------------------- /src/test/scala/br/com/caelum/hibernatequerydsl/TypeSafeAcceptanceTest.scala: -------------------------------------------------------------------------------- 1 | package br.com.caelum.hibernatequerydsl 2 | 3 | import org.hibernate.Session 4 | import org.hibernate.cfg.Configuration 5 | import org.junit.{Test, After, Before} 6 | import org.junit.Assert._ 7 | import br.com.caelum.hibernatequerydsl.PimpedSession._ 8 | import br.com.caelum.hibernatequerydsl.TypeUnsafe._ 9 | class TypeSafeAcceptanceTest { 10 | 11 | private var session:Session = _ 12 | 13 | @Before 14 | def setUp { 15 | val cfg = new Configuration(); 16 | session = cfg.configure().buildSessionFactory().openSession(); 17 | session.beginTransaction(); 18 | } 19 | 20 | @After 21 | def tearDown{ 22 | if (session != null && session.getTransaction().isActive()) { 23 | session.getTransaction().rollback(); 24 | } 25 | } 26 | 27 | private def withUser(name:String=null,age:Int=0, street:String=null) = { 28 | val user = new User 29 | user setName name 30 | user setAge age 31 | session.save(user) 32 | if(street!=null){ 33 | val address = new Address 34 | address setStreet street 35 | address setUser user 36 | session.save(address) 37 | } 38 | this 39 | } 40 | 41 | private def and(name:String=null,age:Int=0, street:String=null) = { 42 | withUser(name, age, street) 43 | } 44 | 45 | @Test 46 | def shouldListAllObjects { 47 | withUser("guilherme").and("alberto") 48 | val users = session.from[User].orderBy(_.getName).asc.list 49 | assertEquals("alberto", users.head.getName) 50 | assertEquals("guilherme", users(1).getName) 51 | } 52 | 53 | 54 | @Test 55 | def shouldSupportComingBackToCriteriaAndAgainToPimped { 56 | withUser("guilherme").and("alberto") 57 | val users = session.from[User].orderBy(_.getName).asc.using(_.setMaxResults(1)).list 58 | assertEquals("alberto", users.head.getName) 59 | assertEquals(1, users.size) 60 | } 61 | 62 | @Test 63 | def shouldSupportOrderingByTwoElements { 64 | withUser("guilherme", 16).and("guilherme", 20) 65 | val users = session.from[User].orderBy(_.getName).asc.orderBy(_.getAge).desc.list 66 | assertEquals(20, users.head.getAge) 67 | assertEquals(16, users(1).getAge) 68 | } 69 | 70 | @Test 71 | def shouldSupportTypeSafeJoining { 72 | withUser("guilherme", 29, "street 1").and("alberto", 26, "street 2") 73 | val addresses = session.from[Address].join(_.getUser).where("user.name" equal "guilherme").list 74 | assertEquals(29, addresses.head.getUser.getAge) 75 | assertEquals(1, addresses.size) 76 | } 77 | 78 | 79 | @Test 80 | def shouldSupportJoiningAndProjectingOnTheBaseObject { 81 | withUser("guilherme", 29, "street 1").and("alberto", 26, "street 2") 82 | val addresses = session.from[Address].join(_.getUser).orderBy(_.getName).list 83 | assertEquals("alberto", addresses.head.getUser.getName) 84 | } 85 | 86 | @Test 87 | def shouldSupportComingBackFromTheOtherGuys { 88 | withUser("guilherme", 29, "Vergueiro").and("guilherme", 26, "Paulista") 89 | val addresses = session.from[Address].join(_.getUser).where("user.name" equal "guilherme").orderBy2[Address](_.getStreet).asc.list 90 | assertEquals(26, addresses.head.getUser.getAge) 91 | } 92 | 93 | } -------------------------------------------------------------------------------- /src/test/scala/br/com/caelum/hibernatequerydsl/User.java: -------------------------------------------------------------------------------- 1 | package br.com.caelum.hibernatequerydsl; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | import javax.persistence.CascadeType; 7 | import javax.persistence.Entity; 8 | import javax.persistence.GeneratedValue; 9 | import javax.persistence.Id; 10 | import javax.persistence.OneToMany; 11 | 12 | @Entity 13 | public class User { 14 | @Id 15 | @GeneratedValue 16 | private Integer id; 17 | private String name; 18 | private Integer age; 19 | @OneToMany(cascade=CascadeType.ALL,mappedBy="user") 20 | private List
addresses = new ArrayList
(); 21 | 22 | 23 | 24 | public List
getAddresses() { 25 | return addresses; 26 | } 27 | 28 | public void setAddresses(List
addresses) { 29 | this.addresses = addresses; 30 | } 31 | 32 | public Integer getId() { 33 | return id; 34 | } 35 | 36 | public void setId(Integer id) { 37 | this.id = id; 38 | } 39 | 40 | public String getName() { 41 | return name; 42 | } 43 | 44 | public void setName(String name) { 45 | this.name = name; 46 | } 47 | 48 | public Integer getAge() { 49 | return age; 50 | } 51 | 52 | public void setAge(Integer age) { 53 | this.age = age; 54 | } 55 | 56 | @Override 57 | public String toString() { 58 | // TODO Auto-generated method stub 59 | return name; 60 | } 61 | 62 | } 63 | --------------------------------------------------------------------------------