Юрий Буянов «Squeryl — ORM с человеческим лицом»

1,933 views

Published on

Published in: Technology, Business
  • Be the first to comment

  • Be the first to like this

Юрий Буянов «Squeryl — ORM с человеческим лицом»

  1. 1. SQUERYL ORM ! "#$%&#"#!() $(*%)!"#$ %&()* e-Legion Ltd., 2011 1
  2. 2. ORMQuery q = entityManager.createQuery( "SELECT AVG(g.scoreInPercentage) FROM Grades g where g.subjectId = :subjectId");q.setParameter(1, mathId);Number avg = (Number) q.getSingleResult();avg.floatValue(); 2
  3. 3. ORMQuery q = entityManager.createQuery( "SELECT AVG(g.scoreInPercentage) FROM Grades g where g.subjectId = :subjectId");q.setParameter(1, mathId);Number avg = (Number) q.getSingleResult();avg.floatValue(); 3
  4. 4. TYPE SAFE ORM (JPA 2)EntityManager em = ...CriteriaBuilder qb = em.getCriteriaBuilder();CriteriaQuery<Person> c = qb.createQuery(Person.class);Root<Person> p = c.from(Person.class);Predicate condition = qb.gt(p.get(Person_.age), 20);c.where(condition);TypedQuery<Person> q = em.createQuery(c);List<Person> olderThan20s = q.getResultList(); 4
  5. 5. SQUERYLORMSQL-+%,%-./0 DSL ,$1 23+4%!%&564%731 6(+(23*(18#.9:# %,3, -%$9:# ,#$3 5
  6. 6. TYPE SAFE ORM (JPA 2)EntityManager em = ...CriteriaBuilder qb = em.getCriteriaBuilder();CriteriaQuery<Person> c = qb.createQuery(Person.class);Root<Person> p = c.from(Person.class);Predicate condition = qb.gt(p.get(Person_.age), 20);c.where(condition);TypedQuery<Person> q = em.createQuery(c);List<Person> olderThan20s = q.getResultList(); 6
  7. 7. SQUERYLval olderThan20s = people.where(_.age gt 20) 7
  8. 8. SQUERYLval olderThan20s = from (people) ( p => select (p) where (p.age gt 20) ) 8
  9. 9. !"#!$% 9
  10. 10. !"#!$%;.(*(3$(23*(1<43.23*((5=#)3InsertSelectUpdateDelete 10
  11. 11. &#&&()&*(&+ import org.squeryl.SessionFactory import java.sql.DriverManager._ Class.forName("org.h2.Driver") SessionFactory.concreteFactory = Some { ()=> Session.create( getConnection("jdbc:h2:mem:"), new H2Adapter ) }“>3(&.31” ?3-4(3;!+%$92@06# ConnectionPool (DBCP, BoneCP) 11
  12. 12. ,-(#*(.&&transaction { ... } &!#7,3 .3"(.3#6 .%&@A 643.23*(A ( %))(6(6 & %.*#inTransaction { ... } .("#7% .# ,#$3#6, #!$( (!+%$92@#6!1 &.@64( ,4@7%0 643.23*(( 12
  13. 13. "/01( (PrimitiveTypeMode) case class User( id: Long = 0, @Column(length = 256) email: String, name: String, rating: Int = 0, ) extends KeyedEntity[Long]Plain Old Scala Object ()%B.% case)563.,346./# 6(+/ ,$1 +%$#0C%$1 )%7@6 -/69 var ($( val8%B.% @32369 432)#4, ()1 !6%$-*3 & -32#>3!$#,%&369 KeyedEntity .# %-1236#$9.% 13
  14. 14. "/01( (CustomTypeMode)5$%B./# $3!!/ ,$1 +%$#08%7@6 &$A"369 & !#-1 &3$(,3*(A, etc 14
  15. 15. "/01( object MySchema extends Schema { val users = table[User] on(users) { u => declare( u.id is (autoIncremented), u.email is (unique) ) } } transaction { MySchema.create }<3-$(*/D743.("#.(15&12( 15
  16. 16. INSERTimport MySchema._val vasya = users.insert(new User("vasya@example.com", "Vasya"))users.insert(List(user1, user2)) 16
  17. 17. SELECTfrom(users) ( u => select(u) where(u.name like “%Vasya%”))from(users) ( u => select(u.id, u.email) orderBy(u.id asc))users.where( _.rating.~ >= 0)//Option[User]users.lookup(1) 17
  18. 18. FULL UPDATE//используем copy//поскольку все поля immutableval updatedVasya = vasya.copy(rating = vasya.rating + 1)users.update(updatedVasya) 18
  19. 19. PARTIAL UPDATE val updated = update(users) ( u => set(u.rating := u.rating.~ + 1) where(u.name like "%Vasya%") ) println("%s Vasyas rated" format updated)~. "6%-/ .# +@6369 Int.+ ( SQL ‘+’&)#!6% ~. )%B.% (!+%$92%&369 u.rating plus 1 19
  20. 20. DELETEusers.delete(1)val deleted = users.deleteWhere( u => u.rating.~ < 0 )println("%s users deleted" format deleted) 20
  21. 21. 2$&3(01"+ 2()450 21
  22. 22. 2$&3(01"+ 2()4505%!63&./# 23+4%!/Group By ( 374#73*(1JoinsRelations 22
  23. 23. COMPOSITE SELECT val rated = users.where( _.rating.~ >= 0) val vasyasRated = from(rated) ( u => select(u) where(u.name like “%Vasya%”) ) 23
  24. 24. NESTED SELECT val rated = users.where( _.rating.~ >= 0) val vasyasRated = from(rated) ( u => select(u) where(u.id in from(rated) (r => select(r.id)) ) ) 24
  25. 25. 067 SELECTC%!643.(".31 &/-%43 from(users) ( u => ... ).page(offset, pageLength)Distinct from(users) ( u => ... ).distinctForUpdate from(users) ( u => ... ).forUpdate 25
  26. 26. (3-03(&+val ratingDistribution = from(users) ( u => groupBy(u.rating) compute(count(u.id)) )ratingDistribution foreach { r=> println(“%s: %s” format (r.key, r.measures))} 26
  27. 27. JOINfrom(users, posts) ( (u,p) => select(u.name, p) where(u.id === p.userId))from(users, avatars.leftOuter) ( (u,a) => select(u, a.url) on(u.id === a.map(_.userId))) 27
  28. 28. RELATIONSobject MySchema extends Schema { val users = table[User] val posts = table[Post] val userPosts = oneToManyRelation(users, posts) via ( (u,p) => u.id === p.userId )} 28
  29. 29. (STATELESS) RELATIONScase class User (....) extends KeyedEntity[Long] { //OneToMany[Post] < Query lazy val posts = MySchema.userPosts.left(this)}case class User (....) extends KeyedEntity[Long] { //ManyToOne[User] < Query lazy val user = MySchema.userPosts.right(this)}val user = users.lookup(1).getOrElse(error(“user not found”))for (p <- user.posts) println(p.title) 29
  30. 30. STATEFUL RELATIONScase class User (....) extends KeyedEntity[Long] { //StatefulOneToMany[Post] < Iterable[Post] lazy val posts = MySchema.userPosts.leftStateful(this)}case User (....) extends KeyedEntity[Long] { //StetefulManyToOne[User] lazy val user = MySchema.userPosts.rightStateful(this)} 30
  31. 31. #02!",(,.& 31
  32. 32. #02!",(,.&Compile-time Voodoo createEqualityExpressionWithLastAccessedFieldReferenceAndConstant>#6 UNION5$(:%) @)./0 DSL where ( u.name === stringOpt.? ) //работает where ( u.flag === boolOpt.? ) //не работает not(not(u.flag)).inhibitWhen(boolOpt != Some(true)) and not(u.flag).inhibitWhen(boolOpt != Some(false)) 32
  33. 33. $!8-!"%? 33
  34. 34. "8("&9!email: yuri.buyanov@e-legion.comemail: yuri.buyanov@gmail.comwww: http://digal.github.com/twitter: @digal 34

×