├── .gitignore
├── src
├── main
│ └── scala
│ │ └── br
│ │ └── com
│ │ └── caelum
│ │ └── hibernatequerydsl
│ │ ├── Transformer.scala
│ │ ├── OrderThis.scala
│ │ ├── Expression.scala
│ │ ├── InvocationMemorizingCallback.scala
│ │ ├── conditions
│ │ └── Cond.scala
│ │ ├── PimpedQuery.scala
│ │ ├── ActiveCollection.scala
│ │ ├── PimpedSession.scala
│ │ └── PimpedCriteria.scala
└── test
│ ├── scala
│ └── br
│ │ └── com
│ │ └── caelum
│ │ └── hibernatequerydsl
│ │ ├── StreetWithName.java
│ │ ├── Address.java
│ │ ├── User.java
│ │ ├── TypeSafeQueryTest.scala
│ │ ├── SessionBased.scala
│ │ ├── TypeSafeAcceptanceTest.scala
│ │ ├── ActiveCollectionAcceptanceTest.scala
│ │ └── PimpedSessionTest.scala
│ └── resources
│ └── hibernate.cfg.xml
├── out
├── production
│ └── hibernate-query-dsl
│ │ └── br
│ │ └── com
│ │ └── caelum
│ │ └── hibernatequerydsl
│ │ ├── OrderThis.scala
│ │ ├── PimpedQuery.scala
│ │ ├── ComparisonCallback.scala
│ │ ├── InvocationMemorizingCallback.scala
│ │ ├── ActiveCollection.scala
│ │ ├── Expression.scala
│ │ ├── PimpedCriteria.scala
│ │ └── PimpedSession.scala
└── test
│ └── hibernate-query-dsl
│ ├── hibernate.cfg.xml
│ └── br
│ └── com
│ └── caelum
│ └── hibernatequerydsl
│ ├── ActiveCollectionAcceptanceTest.scala
│ ├── TypeSafeAcceptanceTest.scala
│ └── PimpedSessionTest.scala
├── README
└── LICENSE
/.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 |
--------------------------------------------------------------------------------
/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/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/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 |
--------------------------------------------------------------------------------
/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/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 |
--------------------------------------------------------------------------------
/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 | @Entity
9 | public class Address {
10 |
11 | @Id
12 | @GeneratedValue
13 | private Integer id;
14 | private String street;
15 | @ManyToOne
16 | private User user;
17 |
18 | public Integer getId() {
19 | return id;
20 | }
21 |
22 | public void setId(Integer id) {
23 | this.id = id;
24 | }
25 |
26 | public String getStreet() {
27 | return street;
28 | }
29 |
30 | public void setStreet(String street) {
31 | this.street = street;
32 | }
33 |
34 | public User getUser() {
35 | return user;
36 | }
37 |
38 | public void setUser(User user) {
39 | this.user = user;
40 | }
41 |
42 | }
43 |
--------------------------------------------------------------------------------
/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 | false
16 | true
17 | update
18 | org.hibernate.cache.HashtableCacheProvider
19 |
20 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/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/test/scala/br/com/caelum/hibernatequerydsl/User.java:
--------------------------------------------------------------------------------
1 | package br.com.caelum.hibernatequerydsl;
2 |
3 | import javax.persistence.*;
4 | import java.util.ArrayList;
5 | import java.util.List;
6 |
7 | @Entity
8 | public class User {
9 | @Id
10 | @GeneratedValue
11 | private Integer id;
12 | private String name;
13 | private Integer age;
14 | @OneToMany(cascade=CascadeType.ALL,mappedBy="user")
15 | private List
addresses = new ArrayList();
16 |
17 |
18 |
19 | public List getAddresses() {
20 | return addresses;
21 | }
22 |
23 | public void setAddresses(List addresses) {
24 | this.addresses = addresses;
25 | }
26 |
27 | public Integer getId() {
28 | return id;
29 | }
30 |
31 | public void setId(Integer id) {
32 | this.id = id;
33 | }
34 |
35 | public String getName() {
36 | return name;
37 | }
38 |
39 | public void setName(String name) {
40 | this.name = name;
41 | }
42 |
43 | public Integer getAge() {
44 | return age;
45 | }
46 |
47 | public void setAge(Integer age) {
48 | this.age = age;
49 | }
50 |
51 | @Override
52 | public String toString() {
53 | // TODO Auto-generated method stub
54 | return name;
55 | }
56 |
57 | }
58 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/src/test/scala/br/com/caelum/hibernatequerydsl/TypeSafeQueryTest.scala:
--------------------------------------------------------------------------------
1 | package br.com.caelum.hibernatequerydsl
2 |
3 | import org.junit.Test
4 | import org.junit.Assert._
5 | import br.com.caelum.hibernatequerydsl.TypeQuerySafe._
6 |
7 | class TypeSafeQueryTest extends SessionBased{
8 |
9 | @Test
10 | def shouldSupportFiltering {
11 | withUser("guilherme", 30).and("aniche").and("alberto").and("guilherme", 29)
12 | val deleted = query.filter(_.getName equal "guilherme").delete
13 | assertEquals(2, deleted)
14 | }
15 |
16 | @Test
17 | def shouldSupportFilteringTypeSafeByType {
18 | val query = new TypeSafeQuery[Address](session)
19 | withUser("aniche").and("alberto")
20 | val guilherme = newUser("guilherme", 29, "rua vergueiro")
21 | val deleted = query.filter(_.getUser equal guilherme).delete
22 | assertEquals(1, deleted)
23 | }
24 |
25 | @Test
26 | def shouldSupportFilteringWithConditional {
27 | withUser("guilherme").and("aniche").and("alberto")
28 | val q = query.filter((u) => (u.getName equal "guilherme") || (u.getName equal "alberto"))
29 | println("Querying " + q)
30 | val deleted = q.delete
31 | assertEquals(2, deleted)
32 | }
33 |
34 | private def query = new TypeSafeQuery[User](session)
35 | }
--------------------------------------------------------------------------------
/src/test/scala/br/com/caelum/hibernatequerydsl/SessionBased.scala:
--------------------------------------------------------------------------------
1 | package br.com.caelum.hibernatequerydsl
2 |
3 | import org.hibernate.Session
4 | import org.hibernate.cfg.Configuration
5 | import org.junit.{After, Before}
6 |
7 | trait SessionBased {
8 | protected var session:Session = _
9 |
10 | def newUser(name:String=null,age:Int=0, street:String=null) = {
11 | val user = new User
12 | user setName name
13 | user setAge age
14 | session.save(user)
15 | if(street!=null){
16 | val address = new Address
17 | address setStreet street
18 | address setUser user
19 | session.save(address)
20 | }
21 | user
22 | }
23 | def withUser(name:String=null,age:Int=0,street:String=null) = {
24 | newUser(name,age,street)
25 | this
26 | }
27 |
28 | def and(name:String=null,age:Int=0, street:String=null) = {
29 | withUser(name, age, street)
30 | }
31 |
32 | @Before
33 | def setUp {
34 | val cfg = new Configuration();
35 | session = cfg.configure().buildSessionFactory().openSession();
36 | session.beginTransaction();
37 | }
38 |
39 | @After
40 | def tearDown{
41 | if (session != null && session.getTransaction().isActive()) {
42 | session.getTransaction().rollback();
43 | }
44 | }
45 |
46 |
47 | }
--------------------------------------------------------------------------------
/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/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 | }
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 = {
28 | val path = properties.mkString(".")
29 | properties = List()
30 | path
31 | }
32 |
33 | def invoke(proxy: AnyRef, method: java.lang.reflect.Method, args: Array[AnyRef]):AnyRef = {
34 | if (method.getDeclaringClass == classOf[Object]) {
35 | return null
36 | }
37 |
38 | _invoked = method.getName
39 | val GetterExpression = """(get|is)?(\w*){1}""".r
40 | _invoked match {
41 | case GetterExpression(_, part2) => {
42 | properties = part2.withFirstCharLowered :: properties
43 | }
44 | }
45 | if(method.getReturnType.getName.eq("boolean"))
46 | new Boolean("false")
47 | else if(method.getReturnType==Char.getClass) {
48 | ' '.asInstanceOf[AnyRef]
49 | } else if(method.getReturnType.isPrimitive) {
50 | 0.asInstanceOf[AnyRef]
51 | } else {
52 | null
53 | }
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/src/main/scala/br/com/caelum/hibernatequerydsl/conditions/Cond.scala:
--------------------------------------------------------------------------------
1 | package br.com.caelum.hibernatequerydsl.conditions
2 |
3 | import net.sf.cglib.proxy.Enhancer
4 | import org.hibernate.criterion.{Criterion, Restrictions}
5 | import scala.collection.mutable.Map
6 | import br.com.caelum.hibernatequerydsl.InvocationMemorizingCallback
7 |
8 | object Cond {
9 | def applyRule[T](f: (T) => Cond)(implicit entityType:Manifest[T]):Cond = {
10 | val handler = new InvocationMemorizingCallback
11 | val proxy = Enhancer.create(entityType.erasure, handler).asInstanceOf[T]
12 | f(proxy)
13 | }
14 | }
15 |
16 | trait Cond {
17 | def crit:Criterion
18 | def content(id:Int):String
19 | def params(id:Int):Map[String, Any]
20 | def ||(g:Cond) = new Or(this, g)
21 | }
22 |
23 | class CriterionCond(val crit:Criterion) extends Cond {
24 | def content(id: Int) = ""
25 |
26 | def params(id: Int) = Map()
27 | }
28 |
29 | /**
30 | * Adds a clause or disjunction to the query.
31 | */
32 | class Or(f:Cond, g:Cond) extends Cond {
33 | def crit = Restrictions.disjunction().add(f.crit).add(g.crit)
34 | def content(id:Int) = "(" + f.content(id) + ") or (" + g.content(id*100) + ")"
35 | def params(id:Int) = f.params(id) ++ g.params(id*100)
36 | }
37 |
38 | /**
39 | * Checks that a field is equal to a specific value,
40 | */
41 | class EqCond(field:String, value:Any) extends Cond {
42 | def crit = Restrictions.eq(field, value)
43 | def content(id:Int) = field + " = :" + field + id
44 | def params(id:Int) = Map((field+id) -> value)
45 | }
46 |
47 | /**
48 | * Checks that a field is null.
49 | */
50 | class IsNull(field:String) extends Cond {
51 | def crit = Restrictions.isNull(field)
52 | def content(id:Int) = field + " is null"
53 | def params(id:Int) = Map()
54 | }
55 |
56 | object Hacker {
57 | private val _field = new ThreadLocal[String]();
58 | def field = {
59 | val x = _field.get
60 | _field.remove
61 | x
62 | }
63 | def uses(x:String) {
64 | _field.set(x)
65 | }
66 | }
67 |
68 |
69 |
70 |
71 |
72 |
--------------------------------------------------------------------------------
/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 extends SessionBased {
10 |
11 | @Test
12 | def shouldListAllObjects {
13 | withUser("guilherme").and("alberto")
14 | val users = session.from[User].orderBy(_.getName).asc.list
15 | assertEquals("alberto", users.head.getName)
16 | assertEquals("guilherme", users(1).getName)
17 | }
18 |
19 |
20 | @Test
21 | def shouldSupportComingBackToCriteriaAndAgainToPimped {
22 | withUser("guilherme").and("alberto")
23 | val users = session.from[User].orderBy(_.getName).asc.using(_.setMaxResults(1)).list
24 | assertEquals("alberto", users.head.getName)
25 | assertEquals(1, users.size)
26 | }
27 |
28 | @Test
29 | def shouldSupportOrderingByTwoElements {
30 | withUser("guilherme", 16).and("guilherme", 20)
31 | val users = session.from[User].orderBy(_.getName).asc.orderBy(_.getAge).desc.list
32 | assertEquals(20, users.head.getAge)
33 | assertEquals(16, users(1).getAge)
34 | }
35 |
36 | @Test
37 | def shouldSupportTypeSafeJoining {
38 | withUser("guilherme", 29, "street 1").and("alberto", 26, "street 2")
39 | val addresses = session.from[Address].join(_.getUser).where("user.name" equal "guilherme").list
40 | assertEquals(29, addresses.head.getUser.getAge)
41 | assertEquals(1, addresses.size)
42 | }
43 |
44 |
45 | @Test
46 | def shouldSupportJoiningAndProjectingOnTheBaseObject {
47 | withUser("guilherme", 29, "street 1").and("alberto", 26, "street 2")
48 | val addresses = session.from[Address].join(_.getUser).orderBy(_.getName).list
49 | assertEquals("alberto", addresses.head.getUser.getName)
50 | }
51 |
52 | @Test
53 | def shouldSupportComingBackFromTheOtherGuys {
54 | withUser("guilherme", 29, "Vergueiro").and("guilherme", 26, "Paulista")
55 | val addresses = session.from[Address].join(_.getUser).where("user.name" equal "guilherme").orderBy2[Address](_.getStreet).asc.list
56 | assertEquals(26, addresses.head.getUser.getAge)
57 | }
58 |
59 | }
--------------------------------------------------------------------------------
/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 | }
--------------------------------------------------------------------------------
/src/main/scala/br/com/caelum/hibernatequerydsl/PimpedQuery.scala:
--------------------------------------------------------------------------------
1 | package br.com.caelum.hibernatequerydsl
2 |
3 | import conditions.Cond
4 | import scala.collection.JavaConversions._
5 | import org.hibernate.{Session, Query}
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 | def apply(params: (String, Any)*) = withParams(params :_*)
24 | }
25 |
26 | class TypeSafeQuery[T](session:Session)(implicit entityType:Manifest[T]) {
27 |
28 | import Cond.applyRule
29 |
30 | private type Myself = TypeSafeQuery[T]
31 | private type Condition = (T) => Cond
32 | private var query = "from " + entityType.erasure.getName
33 | private val params = scala.collection.mutable.Map[String, Any]()
34 | override def toString = "[query " + entityType + " " + query + "]"
35 |
36 | /**
37 | * Applies a filter that will return only one result (Option on it!)
38 | */
39 | def find(f: Condition): Option[T] = {
40 | filter(f)
41 | val q = createQuery("select")
42 | new PimpedQuery(q.setMaxResults(1)).headOption
43 | }
44 |
45 | /**
46 | * Adds a new filter to this query. Still do not execute the query.
47 | */
48 | def filter(f: Condition) = {
49 | val rule = applyRule(f)
50 | if(params.isEmpty) {
51 | query += " where "
52 | } else {
53 | query += " and "
54 | }
55 | val count = params.size + 1
56 | query += rule.content(count)
57 | params ++= rule.params(count)
58 | this
59 | }
60 |
61 | /** Deletes all entries that would otherwise be returned by this query. Lazy delete. */
62 | def delete = createQuery("delete").executeUpdate
63 |
64 | /**
65 | * Forces the execution of this query and returns it as a list
66 | */
67 | def list: List[T] = createQuery("").list.asInstanceOf[java.util.List[T]].toList
68 |
69 | private def createQuery(prefix:String) = {
70 | val q = session.createQuery(prefix + " " + query)
71 | params.foreach((p:Pair[String,Any]) => q.setParameter(p._1, p._2))
72 | q
73 | }
74 | }
75 |
--------------------------------------------------------------------------------
/src/main/scala/br/com/caelum/hibernatequerydsl/ActiveCollection.scala:
--------------------------------------------------------------------------------
1 | package br.com.caelum.hibernatequerydsl
2 |
3 | import conditions.Cond
4 | import org.hibernate.criterion.Restrictions
5 | import net.sf.cglib.proxy.Enhancer
6 |
7 | class ActiveCollection[T](var elements:List[T], query:PimpedCriteria[T,T])(implicit entityType:Manifest[T]) {
8 |
9 | import Cond.applyRule
10 | private type Myself = ActiveCollection[T]
11 | private type Condition = (T) => Cond
12 | private def loaded = Option(elements).isDefined
13 |
14 | private implicit def listToAC(l:List[T]):Myself = new Myself(elements, null)
15 | private implicit def queryToAC(q:PimpedCriteria[T,T]):Myself = new Myself(null, q)
16 |
17 | def grabThem():List[T] = {
18 | if(!loaded) {
19 | elements = query.asList[T].toList
20 | }
21 | elements
22 | }
23 |
24 | def take(k: Int):Myself = {
25 | query.using(_.setMaxResults(k))
26 | }
27 |
28 | def drop(k:Int): Myself = {
29 | query.using(_.setFirstResult(k))
30 | }
31 |
32 | def dropWhile(f:(T) => Boolean) = {
33 | grabThem.dropWhile(f)
34 | }
35 |
36 | def exists(f: Condition) = find(f).isDefined
37 |
38 | def filter(f: Condition):Myself = {
39 | query.and(applyRule(f).crit)
40 | }
41 |
42 | def withFilter(f: Condition):Myself = filter(f)
43 |
44 | def filterNot(f: Condition):Myself = query.and(Restrictions.not(applyRule(f).crit))
45 |
46 | def find(f: Condition): Option[T] = {
47 | query.and(applyRule(f).crit).using(_.setMaxResults(1)).headOption
48 | }
49 |
50 | def count(f: Condition) = {
51 | filter(f)
52 | query.count
53 | }
54 |
55 | def head = query.headOption.get
56 | def tail:List[T] = drop(1).grabThem
57 |
58 |
59 | def map[B](f: T => B)(implicit m:Manifest[B]):ActiveCollection[B] = {
60 | val handler = new InvocationMemorizingCallback
61 | val proxy = Enhancer.create(entityType.erasure, handler).asInstanceOf[T]
62 | f(proxy)
63 |
64 | val field = handler.invokedPath
65 | if (!field.isEmpty)
66 | query.select(field)
67 |
68 | new ActiveCollection[B](null, query.asInstanceOf[PimpedCriteria[B,B]])
69 | }
70 | def flatMap[B](f: T => Seq[B])(implicit m:Manifest[B]):ActiveCollection[B] = {
71 | val handler = new InvocationMemorizingCallback
72 | val proxy = Enhancer.create(entityType.erasure, handler).asInstanceOf[T]
73 | f(proxy)
74 |
75 | val field = handler.invokedPath
76 | if (!field.isEmpty)
77 | query.select(field)
78 |
79 | new ActiveCollection[B](null, query.asInstanceOf[PimpedCriteria[B,B]])
80 | }
81 | }
--------------------------------------------------------------------------------
/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 | }
--------------------------------------------------------------------------------
/src/test/scala/br/com/caelum/hibernatequerydsl/ActiveCollectionAcceptanceTest.scala:
--------------------------------------------------------------------------------
1 | package br.com.caelum.hibernatequerydsl
2 |
3 | import org.junit.Test
4 | import org.junit.Assert._
5 | import br.com.caelum.hibernatequerydsl.PimpedSession._
6 | import TypeSafe._
7 |
8 | class ActiveCollectionAcceptanceTest extends SessionBased {
9 |
10 | def ar = new ActiveCollection[User](null, session.from[User])
11 |
12 | @Test
13 | def shouldSupportTake {
14 | withUser("guilherme").and("alberto")
15 | val users = ar.take(1)
16 | assertEquals("guilherme", users(0).getName)
17 | assertEquals(1, users.toList.size)
18 | }
19 |
20 | @Test
21 | def shouldSupportParametersCombinedWithTake {
22 | withUser("guilherme").and("alberto")
23 | val users = ar.filter(_.getName equal "alberto").take(1)
24 | assertEquals("alberto", users(0).getName)
25 | assertEquals(1, users.size)
26 | }
27 |
28 | @Test
29 | def shouldSupportParametersWithInt {
30 | withUser("guilherme", 20).and("alberto", 18)
31 | val users = ar.filter(_.getAge \== 20)
32 | assertEquals("guilherme", users(0).getName)
33 | assertEquals(1, users.size)
34 | }
35 |
36 |
37 | @Test
38 | def shouldSupportFindingAnElement {
39 | withUser("guilherme", 29).and("alberto").and("guilherme", 30)
40 | val users = ar.find(_.getName equal "guilherme")
41 | assertEquals(29, users.get.getAge)
42 | }
43 |
44 | @Test
45 | def shouldSupportDroppingSomething {
46 | withUser("guilherme", 29).and("alberto").and("guilherme", 30)
47 | val users = ar.filter(_.getName equal "guilherme").drop(1)
48 | assertEquals(30, users.head.getAge)
49 | }
50 |
51 |
52 |
53 | @Test
54 | def shouldSupportCheckingIfAnElementExists {
55 | withUser("guilherme").and("alberto")
56 | assertTrue(ar.exists(_.getName equal "alberto"))
57 | assertFalse(ar.exists(_.getName equal "marcos"))
58 | }
59 |
60 | @Test
61 | def shouldSupportGrabbingAll {
62 | withUser("guilherme").and("alberto")
63 | val users:List[User] = ar
64 | assertEquals(2, users.size)
65 | }
66 |
67 | @Test
68 | def shouldSupportRegrabbing {
69 | withUser("guilherme").and("alberto")
70 | val users = ar
71 | assertEquals(2, users.size)
72 | assertEquals(classOf[ActiveCollection[User]], ar.getClass)
73 | assertEquals(1, users.take(1).size)
74 | }
75 |
76 | @Test
77 | def shouldSupportForExpressions {
78 | withUser("guilherme", 20).and("alberto", 30).and("alberto", 20)
79 |
80 | val users = for {
81 | u <- ar
82 | if u.getName equal "alberto"
83 | } yield u
84 |
85 | assertEquals(2, users.size)
86 | }
87 |
88 | @Test
89 | def shouldSupportForExpressionsWithSeveralFilters {
90 | withUser("guilherme", 20).and("alberto", 30).and("alberto", 20)
91 |
92 | val users = for {
93 | u <- ar
94 | if u.getName equal "alberto"
95 | if u.getAge \< 21
96 | } yield u
97 |
98 | assertEquals(1, users.size)
99 | }
100 | @Test
101 | def shouldSupportForExpressionsWithSelect {
102 | withUser("guilherme", 20).and("alberto", 30).and("alberto", 20)
103 |
104 | val userNames = for {
105 | u <- ar
106 | if u.getAge \< 21
107 | } yield u.getName
108 |
109 | assertEquals(List("guilherme", "alberto"), userNames.grabThem)
110 | }
111 |
112 | }
--------------------------------------------------------------------------------
/src/main/scala/br/com/caelum/hibernatequerydsl/PimpedSession.scala:
--------------------------------------------------------------------------------
1 | package br.com.caelum.hibernatequerydsl
2 |
3 | import conditions.{EqCond, CriterionCond}
4 | import org.hibernate.{ Session, Query }
5 | import scala.reflect.{Apply, Select, Literal, Tree,Code,This }
6 | import java.io.Serializable
7 | import org.hibernate.criterion._
8 | import br.com.caelum.hibernatequerydsl.TypeQuerySafe.X
9 |
10 | object PimpedSession {
11 |
12 | implicit def session2PimpedSession(session: Session) = new PimpedSession(session)
13 |
14 | implicit def pimpedCriteria2Criteria[T, P](pimped: PimpedCriteria[T, P]) = pimped.criteria
15 |
16 | implicit def hibernateQuery2PimpedQuery(query: Query) = new PimpedQuery(query)
17 |
18 | implicit def orderThisToPimped[T, P](order: OrderThis[T, P]) = order.asc
19 |
20 | implicit def criteriaToActive[T](criteria:PimpedCriteria[T,T])(implicit t:Manifest[T]) = new ActiveCollection[T](null, criteria)
21 |
22 | implicit def acToList[T](ac: ActiveCollection[T]) = ac.grabThem
23 |
24 | implicit def queryToList[T](query:TypeSafeQuery[T]) = query.list
25 |
26 | implicit def sessionToQueriable(session: Session) = new {
27 | def query[T](implicit manifest:Manifest[T]) = new TypeSafeQuery[T](session)(manifest)
28 | }
29 |
30 | }
31 |
32 | object TypeUnsafe {
33 | implicit def string2PimpedStringCondition(field: String) = new PimpedStringCondition(field)
34 | }
35 |
36 | object TypeSafe {
37 | implicit def anything2TypeSafeCondition(qq: Any) = new TypeSafeCriteriaCondition(Pig.tl.get)
38 |
39 | implicit def criterion2Cond(crit:Criterion) = new CriterionCond(crit)
40 | }
41 |
42 | object TypeQuerySafe {
43 |
44 |
45 | implicit def anyToEq(qq:Any) = new X(Pig.tl.get)
46 |
47 | class X(proxy:InvocationMemorizingCallback) {
48 | val field = proxy.prefix + proxy.invokedPath
49 | def equal(other:Any) = new EqCond(field, other)
50 | }
51 | }
52 |
53 | class TypeSafeCriteriaCondition(proxy: InvocationMemorizingCallback) {
54 |
55 | val field = proxy.prefix + proxy.invokedPath
56 |
57 | def equal(value: Any) = Restrictions.eq(field, value)
58 |
59 | def \==(value: Any) = Restrictions.eq(field, value)
60 |
61 | def \>(value: Any) = Restrictions.gt(field, value)
62 |
63 | def \>=(value: Any) = Restrictions.ge(field, value)
64 |
65 | def \<(value: Any) = Restrictions.lt(field, value)
66 |
67 | def \<=(value: Any) = Restrictions.le(field, value)
68 |
69 | def \!=(value: Any) = Restrictions.ne(field, value)
70 |
71 | def like(value: String) = Restrictions.ilike(field, value, MatchMode.ANYWHERE)
72 |
73 | def isNull = Restrictions.isNull(field)
74 |
75 | def isNotNull = Restrictions.isNotNull(field)
76 |
77 | def alias(newName: String) = Projections.property(field).as(newName)
78 | }
79 |
80 | class PimpedStringCondition(field: String) {
81 | def equal(value: Any) = Restrictions.eq(field, value)
82 |
83 | def >(value: Any) = Restrictions.gt(field, value)
84 |
85 | def >=(value: Any) = Restrictions.ge(field, value)
86 |
87 | def <(value: Any) = Restrictions.lt(field, value)
88 |
89 | def <=(value: Any) = Restrictions.le(field, value)
90 |
91 | def !==(value: Any) = Restrictions.ne(field, value)
92 |
93 | def like(value: String) = Restrictions.ilike(field, value, MatchMode.ANYWHERE)
94 |
95 | def isNull = Restrictions.isNull(field)
96 |
97 | def isNotNull = Restrictions.isNotNull(field)
98 |
99 | def desc = Order.desc(field)
100 |
101 | def asc = Order.asc(field)
102 |
103 | def alias(newName: String) = Projections.property(field).as(newName)
104 |
105 | }
106 |
107 | class PimpedSession(session: Session) {
108 |
109 | def all[T](implicit manifest: Manifest[T]) = {
110 | from[T].list
111 | }
112 |
113 | def from[T](implicit manifest: Manifest[T]) = {
114 | val criteria = session.createCriteria(manifest.erasure)
115 | new PimpedCriteria[T, T]("", criteria)
116 | }
117 |
118 | def query(query: String) = session.createQuery(query)
119 |
120 | def count[T](implicit manifest: Manifest[T]) = from[T].count
121 |
122 | def exists[T](implicit manifest: Manifest[T]) = count[T] > 0
123 |
124 | def first[T](implicit manifest: Manifest[T]) = from[T].first[T]
125 |
126 | def last[T](implicit manifest: Manifest[T]) = from[T].last[T]
127 |
128 | def load[T](implicit manifest: Manifest[T], id: Serializable) = {
129 | session.load(manifest.erasure, id).asInstanceOf[T]
130 | }
131 |
132 | }
133 |
134 |
135 |
136 |
--------------------------------------------------------------------------------
/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/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 |
--------------------------------------------------------------------------------
/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 = where(condition)
97 |
98 | def and(f: (T) => Criterion)(implicit entityType: Manifest[T]): Myself = where(f)
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/test/scala/br/com/caelum/hibernatequerydsl/PimpedSessionTest.scala:
--------------------------------------------------------------------------------
1 | package br.com.caelum.hibernatequerydsl
2 |
3 | import org.junit.Ignore
4 | import org.hibernate.cfg.Configuration
5 | import br.com.caelum.hibernatequerydsl.PimpedSession._
6 | import org.hibernate.Session
7 | import org.junit.{ Test, Before, After }
8 | import org.junit.Assert._
9 | import br.com.caelum.hibernatequerydsl.TypeSafe._
10 |
11 | class PimpedClassTest {
12 |
13 | private var session: Session = _
14 | private val userToQuery = new User
15 | private val addressToQuery = new Address
16 |
17 | @Before
18 | def setUp {
19 | val cfg = new Configuration();
20 | //cfg.configure().setProperty("hibernate.connection.url", "jdbc:hsqldb:mem:mydvdsDB");
21 | session = cfg.configure().buildSessionFactory().openSession();
22 | session.beginTransaction();
23 | }
24 |
25 | /**
26 | * Undoing all changes to database
27 | * @throws Exception
28 | */
29 | @After
30 | def tearDown {
31 | if (session != null && session.getTransaction().isActive()) {
32 | session.getTransaction().rollback();
33 | }
34 | }
35 |
36 | private def newUser(name: String = null, age: Int = 0) = {
37 | val user = new User
38 | user setName name
39 | user setAge age
40 | session.save(user)
41 | user
42 | }
43 |
44 | private def newAddress(street: String, user: User) = {
45 | val address = new Address
46 | address setStreet street
47 | address setUser user
48 | session.save(address)
49 | address
50 | }
51 |
52 | @Test
53 | def shouldListAllObjects {
54 | newUser("alberto")
55 | newUser("alberto")
56 | val users = session.all[User]
57 | assertEquals(2, users size)
58 | }
59 |
60 | @Test
61 | def shouldVerifyIfExists {
62 | newUser("alberto")
63 | assertTrue(session.exists[User])
64 | }
65 |
66 | @Test
67 | def shouldVerifyIfNotExists {
68 | assertFalse(session.exists[User])
69 | }
70 |
71 | @Test
72 | def shouldCount {
73 | newUser("alberto")
74 | newUser("alberto")
75 | assertEquals(2, session.count[User])
76 | }
77 |
78 | @Test
79 | def shouldGetFirstBasedOnId {
80 | val alberto = newUser("alberto")
81 | newUser("alberto2")
82 | val userRetrieved = session.first[User]
83 | assertEquals(alberto, userRetrieved)
84 | }
85 |
86 | @Test
87 | def shouldGetFirstBasedOnSomeField {
88 | val alberto = newUser("alberto")
89 | val joao = newUser("joao")
90 | val userRetrieved = session.from[User].orderBy(_.getName).desc.first[User]
91 | assertEquals(joao, userRetrieved)
92 | }
93 |
94 | @Test
95 | def shouldGetTheLastBasedOnId {
96 | val alberto = newUser("alberto")
97 | val joao = newUser("joao")
98 | val userRetrieved = session.last[User]
99 | assertEquals(joao, userRetrieved)
100 | }
101 |
102 | @Test
103 | def shouldGetTheLastDescOrderedOnSomeField {
104 | val alberto = newUser("alberto")
105 | val joao = newUser("joao")
106 | val userRetrieved = session.from[User].orderBy(_.getName).desc.last[User]
107 | assertEquals(alberto, userRetrieved)
108 | }
109 |
110 | @Test
111 | def shouldGetTheLastDescOrderedOnSomeFields {
112 | val alberto = newUser("alberto")
113 | val joao = newUser("joao")
114 | val userRetrieved = session.from[User].orderBy(_.getName).desc.last[User]
115 | assertEquals(alberto, userRetrieved)
116 | }
117 |
118 | @Test
119 | def shouldGetTheLastAscOrderedOnSomeField {
120 | val alberto = newUser("alberto")
121 | val joao = newUser("joao")
122 | val userRetrieved = session.from[User].orderBy(_.getName).asc.last[User]
123 | assertEquals(joao, userRetrieved)
124 | }
125 |
126 | @Test
127 | def shouldGetTheLastAscAndDescOrderedOnSomeFields {
128 | val alberto = newUser("alberto", 10)
129 | val alberto2 = newUser("alberto", 20)
130 | val userRetrieved = session.from[User].orderBy(_.getName).asc.orderBy(_.getAge).desc.last[User]
131 | assertEquals(alberto, userRetrieved)
132 | }
133 |
134 | @Test
135 | def shouldDoASimpleJoin {
136 | val alberto = newUser("alberto")
137 | val address = newAddress("rua da casa de nao sei quem", alberto)
138 | val address2 = newAddress("rua da casa de nao sei quem", alberto)
139 | val list = session.from[Address].join(_.getUser).asList[Address]
140 | assertEquals(2, list size)
141 |
142 | }
143 |
144 | @Test
145 | def shouldDoASimpleJoinBasedOnSomeField1 {
146 | val alberto = newUser("alberto")
147 | val alberto2 = newUser("alberto2")
148 | val address = newAddress("rua da casa de nao sei quem", alberto)
149 | val address2 = newAddress("rua da casa de nao sei quem", alberto2)
150 | //pimpedCondition(_.getName).\==("alberto2")
151 | val list = session.from[Address].join(_.getUser).where(_.getName.\==("alberto2")).asList[Address]
152 | assertEquals(1, list size)
153 |
154 | }
155 |
156 | @Test
157 | def shouldDoASimpleJoinBasedOnSomeFieldsWithAnd {
158 | val alberto = newUser("alberto", 10)
159 | val alberto2 = newUser("alberto2", 20)
160 | val address = newAddress("rua da casa de nao sei quem", alberto)
161 | val address2 = newAddress("rua da casa de nao sei quem", alberto2)
162 | val list = session.from[Address].join(_.getUser).where(_.getName \== ("alberto2")).where(_.getAge \== alberto2.getAge).asList[Address]
163 | assertEquals(1, list size)
164 | }
165 |
166 | @Test
167 | def shouldDoASimpleQueryBasedOnSomeFields1 {
168 | val alberto = newUser("alberto", 10)
169 | val alberto2 = newUser("alberto2", 20)
170 | val alberto3 = newUser("alberto3", 30)
171 | val alberto4 = newUser("alberto4", 40)
172 | val list = session.from[User].where(_.getAge \> alberto.getAge).asList[User]
173 | assertEquals(3, list size)
174 | }
175 |
176 | @Test
177 | def shouldDoASimpleQueryBasedOnSomeFields2 {
178 | val alberto = newUser("alberto", 10)
179 | val alberto2 = newUser("alberto2", 20)
180 | val alberto3 = newUser("alberto3", 30)
181 | val alberto4 = newUser("alberto4", 40)
182 | var list = session.from[User].where(_.getAge \>= alberto.getAge).asList[User]
183 | assertEquals(4, list size)
184 | }
185 |
186 | @Test
187 | def shouldDoASimpleQueryBasedOnSomeFields3 {
188 | val alberto = newUser("alberto", 10)
189 | val alberto2 = newUser("alberto2", 20)
190 | val alberto3 = newUser("alberto3", 30)
191 | val alberto4 = newUser("alberto4", 40)
192 | val list = session.from[User].where(_.getAge \< alberto2.getAge).asList[User]
193 | assertEquals(1, list size)
194 | }
195 |
196 | @Test
197 | def shouldDoASimpleQueryBasedOnSomeFields4 {
198 | val alberto = newUser("alberto", 10)
199 | val alberto2 = newUser("alberto2", 20)
200 | val alberto3 = newUser("alberto3", 30)
201 | val alberto4 = newUser("alberto4", 40)
202 | val list = session.from[User].where(_.getAge \<= alberto2.getAge).asList[User]
203 | assertEquals(2, list size)
204 | }
205 |
206 | @Test
207 | def shouldDoASimpleQueryBasedOnSomeFields5 {
208 | val alberto = newUser("alberto", 10)
209 | val alberto2 = newUser("alberto2", 20)
210 | val alberto3 = newUser("alberto3", 30)
211 | val alberto4 = newUser("outrute", 40)
212 | val list = session.from[User].where(_.getAge \>= alberto2.getAge).where(_.getName like "alberto").asList[User]
213 | assertEquals(2, list size)
214 | }
215 |
216 | @Test
217 | def shouldDoASimpleQueryBasedOnSomeFields6 {
218 | val alberto = newUser(null, 10)
219 | val alberto2 = newUser("alberto2", 20)
220 | val alberto3 = newUser("alberto3", 30)
221 | val alberto4 = newUser("outrute", 40)
222 | val list = session.from[User].where(_.getName isNull).asList[User]
223 | assertEquals(1, list size)
224 | }
225 |
226 | @Test
227 | def shouldDoASimpleQueryBasedOnSomeFields7 {
228 | val alberto = newUser(null, 10)
229 | val alberto2 = newUser("alberto2", 20)
230 | val alberto3 = newUser("alberto3", 30)
231 | val alberto4 = newUser("outrute", 40)
232 | val list = session.from[User].where(_.getName isNotNull).asList[User]
233 | assertEquals(3, list size)
234 | }
235 |
236 | @Test
237 | def shouldDoASimpleQueryBasedOnSomeFields8 {
238 | val alberto = newUser("alberto", 10)
239 | val alberto2 = newUser("alberto2", 20)
240 | val alberto3 = newUser("alberto3", 30)
241 | val alberto4 = newUser("alberto4", 40)
242 | val list = session.from[User].where(_.getName \!= "alberto").asList[User]
243 | assertEquals(3, list size)
244 | }
245 |
246 | @Test
247 | def shouldExecuteJustASimpleHQL {
248 | val alberto = newUser("alberto", 10)
249 | val alberto2 = newUser("alberto2", 20)
250 | val alberto3 = newUser("alberto3", 30)
251 | val alberto4 = newUser("outrute", 40)
252 | val list = session.query("from User").asList[User]
253 | assertEquals(4, list size)
254 | }
255 |
256 | @Test
257 | def shouldAssingParametersForHQL {
258 | val alberto = newUser("alberto", 10)
259 | val alberto2 = newUser("alberto2", 20)
260 | val alberto3 = newUser("alberto3", 30)
261 | val alberto4 = newUser("outrute", 40)
262 | val list = session.query("from User where name=:name and age =:age").withParams("name" -> "alberto", "age" -> alberto.getAge).asList[User]
263 | assertEquals(1, list size)
264 | }
265 |
266 | @Test
267 | def shouldGroupUserByStreet {
268 | val alberto = newUser("alberto", 10)
269 | val alberto2 = newUser("alberto2", 20)
270 | val alberto3 = newUser("alberto3", 15)
271 | val alberto4 = newUser("alberto4", 30)
272 | val address = newAddress("x", alberto)
273 | val address2 = newAddress("x", alberto2)
274 | val address3 = newAddress("y", alberto3)
275 | val address4 = newAddress("y", alberto4)
276 | val list = session.from[User].join(_.getAddresses).groupBy("addresses.street").asList[User]
277 | assertEquals(2, list size)
278 | }
279 |
280 | @Test
281 | def shouldGroupUserByStreetWithAvgAge {
282 | val alberto = newUser("alberto", 10)
283 | val alberto2 = newUser("alberto2", 20)
284 | val alberto3 = newUser("alberto3", 15)
285 | val alberto4 = newUser("alberto4", 30)
286 | val address = newAddress("x", alberto)
287 | val address2 = newAddress("x", alberto2)
288 | val address3 = newAddress("y", alberto3)
289 | val address4 = newAddress("y", alberto4)
290 | val list = session.from[User].join(_.getAddresses).groupBy("addresses.street").avg[User](_.getAge).asList[Array[Object]]
291 | assertEquals(2, list size)
292 | assertEquals(15.0, list.head(1))
293 | }
294 |
295 | @Test
296 | def shouldGroupUserByStreetWithSumAge {
297 | val alberto = newUser("alberto", 10)
298 | val alberto2 = newUser("alberto2", 20)
299 | val alberto3 = newUser("alberto3", 15)
300 | val alberto4 = newUser("alberto4", 30)
301 | val address = newAddress("x", alberto)
302 | val address2 = newAddress("x", alberto2)
303 | val address3 = newAddress("y", alberto3)
304 | val address4 = newAddress("y", alberto4)
305 | val list = session.from[User].join(_.getAddresses).groupBy("addresses.street").sum[User](_.getAge).asList[Array[Object]]
306 | assertEquals(2, list size)
307 | assertEquals(30L, list.head(1))
308 | }
309 |
310 | @Test
311 | def shouldGroupUserByStreetWithCountAge {
312 | val alberto = newUser("alberto", 10)
313 | val alberto2 = newUser("alberto2", 20)
314 | val alberto3 = newUser("alberto3", 15)
315 | val alberto4 = newUser("alberto4", 30)
316 | val address = newAddress("x", alberto)
317 | val address2 = newAddress("x", alberto2)
318 | val address3 = newAddress("y", alberto3)
319 | val address4 = newAddress("y", alberto4)
320 | val list = session.from[User].join(_.getAddresses).groupBy("addresses.street").count[User](_.getAge).asList[Array[Object]]
321 | assertEquals(2, list size)
322 | assertEquals(2L, list.head(1))
323 | }
324 |
325 | @Test
326 | def shouldListJustUsersWithAddresses {
327 | val alberto = newUser("alberto", 10)
328 | val alberto2 = newUser("alberto2", 20)
329 | val alberto3 = newUser("alberto3", 15)
330 | val alberto4 = newUser("alberto4", 30)
331 | val address = newAddress("x", alberto)
332 | val address2 = newAddress("x", alberto2)
333 | val address3 = newAddress("y", alberto3)
334 |
335 | val list = session.from[User].where.has(_.getAddresses).asList[User]
336 | assertEquals(3, list size)
337 | }
338 |
339 | @Test
340 | def shouldListJustUsersWithAddressesFilteringBySomeAttribute {
341 | val alberto = newUser("alberto", 10)
342 | val alberto2 = newUser("alberto2", 20)
343 | val alberto3 = newUser("alberto3", 15)
344 | val alberto4 = newUser("alberto4", 30)
345 | val address = newAddress("x", alberto)
346 | val address2 = newAddress("x", alberto2)
347 | val address3 = newAddress("y", alberto3)
348 | import br.com.caelum.hibernatequerydsl.TypeUnsafe._
349 | val list = session.from[User].includes(_.getAddresses).where("addresses.street" equal "y").asList[User]
350 | assertEquals(1, list size)
351 | }
352 |
353 | @Test
354 | def shouldListJustUsersWithAddressesFilteringBySomeAttribute2 {
355 | val alberto = newUser("alberto", 10)
356 | val alberto2 = newUser("alberto2", 20)
357 | val alberto3 = newUser("alberto3", 15)
358 | val alberto4 = newUser("alberto4", 30)
359 | val address = newAddress("x", alberto)
360 | val address2 = newAddress("x", alberto2)
361 | val address3 = newAddress("y", alberto3)
362 | import br.com.caelum.hibernatequerydsl.TypeUnsafe._
363 | val list = session.from[User].includes(_.getAddresses).where("addresses.street" equal "y").asList[User]
364 | assertEquals(1, list size)
365 | }
366 |
367 | @Test
368 | def shouldSelectByFields {
369 | val alberto = newUser("alberto", 10)
370 | val alberto2 = newUser("alberto2", 20)
371 | val alberto3 = newUser("alberto3", 15)
372 | val alberto4 = newUser("alberto4", 30)
373 | val address = newAddress("x", alberto)
374 | val address2 = newAddress("x", alberto2)
375 | val address3 = newAddress("y", alberto3)
376 | val list = session.from[User].select("name").asList[String]
377 | assertEquals("alberto", list.head)
378 | }
379 |
380 | @Test
381 | def shouldSelectDistinctedObjects {
382 | val alberto = newUser("alberto", 10)
383 | val alberto2 = newUser("alberto", 20)
384 | val alberto3 = newUser("alberto", 15)
385 | val alberto4 = newUser("alberto4", 30)
386 | val list = session.from[User].distinct(_.getName).asList[String]
387 | assertEquals(2, list.size)
388 | }
389 |
390 | @Ignore //TODO fazer o resulttransformer funcionar.
391 | def shouldTransformArrayToMyResultTransformer {
392 | val alberto = newUser("alberto", 10)
393 | val alberto2 = newUser("alberto2", 20)
394 | val alberto3 = newUser("alberto3", 15)
395 |
396 | val alberto4 = newUser("alberto4", 30)
397 | val address = newAddress("x", alberto)
398 | val address2 = newAddress("x", alberto2)
399 | val address3 = newAddress("y", alberto3)
400 | val list = session.from[User].join(_.getAddresses).select("name").selectWithAliases("addresses.street".alias("street")).transformToBean[StreetWithName].asList
401 | assertEquals("alberto", list.head.getName)
402 | }
403 | }
404 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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!
--------------------------------------------------------------------------------