SlideShare a Scribd company logo
SQUERYL
              ORM ! "#$%&#"#!'() $(*%)




!"#$ %&'()*                         e-Legion Ltd., 2011
                                                      1
ORM



Query 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
ORM



Query 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
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
SQUERYL


ORM

SQL-+%,%-./0 DSL ,$1 23+4%!%&

564%731 6(+(23*(1

8#.9:# '%,3, -%$9:# ,#$3




                                5
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
SQUERYL




val olderThan20s = people.where(_.age gt 20)




                                               7
SQUERYL



val olderThan20s =

 from (people) ( p =>
   select (p)
   where (p.age gt 20)
 )




                         8
!"#!$%




         9
!"#!$%

;.(*(3$(23*(1
<43.23'*((
5=#)3
Insert
Select

Update
Delete


                      10
&#&'&()&*('&+
 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
,-(#*(.'&&


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
"/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 +%$#0
C%$1 )%7@6 -/69 var ($( val
8%B.% @'32369 432)#4, ()1 !6%$-*3 & -32#
>3!$#,%&369 KeyedEntity .# %-1236#$9.%


                                            13
"/01(
             (CustomTypeMode)




5$%B./# '$3!!/ ,$1 +%$#0
8%7@6 &'$A"369 & !#-1 &3$(,3*(A, etc




                                       14
"/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.("#.(1
5&12(

                                                  15
INSERT



import MySchema._

val vasya =
  users.insert(new User("vasya@example.com", "Vasya"))

users.insert(List(user1, user2))




                                                         16
SELECT
from(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
FULL UPDATE



//используем copy
//поскольку все поля immutable

val updatedVasya =
  vasya.copy(rating = vasya.rating + 1)

users.update(updatedVasya)




                                          18
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
DELETE


users.delete(1)

val deleted =
  users.deleteWhere( u =>
    u.rating.~ < 0
  )

println("%s users deleted" format deleted)




                                             20
2$&3(01"+ 2()450




                   21
2$&3(01"+ 2()450


5%!63&./# 23+4%!/
Group By ( 374#73*(1
Joins
Relations




                       22
COMPOSITE SELECT


   val rated =
     users.where( _.rating.~ >= 0)


   val vasyasRated =
     from(rated) ( u =>
       select(u)
       where(u.name like “%Vasya%”)
     )




                                      23
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
067 SELECT

C%!643.(".31 &/-%4'3
  from(users) ( u => ... ).page(offset, pageLength)


Distinct
  from(users) ( u => ... ).distinct


ForUpdate
  from(users) ( u => ... ).forUpdate




                                                      25
(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
JOIN


from(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
RELATIONS



object MySchema extends Schema {
  val users = table[User]
  val posts = table[Post]
  val userPosts =
   oneToManyRelation(users, posts) via ( (u,p) =>
     u.id === p.userId
   )
}




                                                    28
(STATELESS) RELATIONS

case 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
STATEFUL RELATIONS

case 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
#02!",(,.&




             31
#02!",(,.&

Compile-time Voodoo
  createEqualityExpressionWithLastAccessedFieldReferenceAndConstant


>#6 UNION
5$(:'%) @)./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
$!8-!"%?




           33
"8("&9!


email: yuri.buyanov@e-legion.com

email: yuri.buyanov@gmail.com

www: http://digal.github.com/

twitter: @digal




                                   34

More Related Content

KEY
JQuery In Rails
Louie Zhao
 
PDF
Jquery In Rails
shen liu
 
PDF
PhoneGap: Local Storage
Ivano Malavolta
 
PDF
Command-Oriented Architecture
Luiz Messias
 
PDF
Modern Application Foundations: Underscore and Twitter Bootstrap
Howard Lewis Ship
 
PDF
SQLAlchemy Seminar
Yury Yurevich
 
PPT
Kick start with j query
Md. Ziaul Haq
 
PDF
Ruby Language - A quick tour
aztack
 
JQuery In Rails
Louie Zhao
 
Jquery In Rails
shen liu
 
PhoneGap: Local Storage
Ivano Malavolta
 
Command-Oriented Architecture
Luiz Messias
 
Modern Application Foundations: Underscore and Twitter Bootstrap
Howard Lewis Ship
 
SQLAlchemy Seminar
Yury Yurevich
 
Kick start with j query
Md. Ziaul Haq
 
Ruby Language - A quick tour
aztack
 

What's hot (20)

PDF
Delivering a Responsive UI
Rebecca Murphey
 
PDF
Idioms in swift 2016 05c
Kaz Yoshikawa
 
KEY
Advanced jQuery
sergioafp
 
PDF
DOM Scripting Toolkit - jQuery
Remy Sharp
 
PDF
Beyond the DOM: Sane Structure for JS Apps
Rebecca Murphey
 
ODP
Javascript & jQuery: A pragmatic introduction
Iban Martinez
 
PDF
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기
Suyeol Jeon
 
PPT
Drupal csu-open atriumname
Emanuele Quinto
 
PDF
DataMapper @ RubyEnRails2009
Dirkjan Bussink
 
PDF
The Ring programming language version 1.5.2 book - Part 43 of 181
Mahmoud Samir Fayed
 
PDF
Rediscovering JavaScript: The Language Behind The Libraries
Simon Willison
 
PDF
Functionality Focused Code Organization
Rebecca Murphey
 
PPTX
jQuery
Jay Poojara
 
DOCX
Miniproject on Employee Management using Perl/Database.
Sanchit Raut
 
PDF
Elm: give it a try
Eugene Zharkov
 
PDF
画像Hacks
Yusuke Wada
 
PDF
Dig Deeper into WordPress - WD Meetup Cairo
Mohamed Mosaad
 
ODT
linieaire regressie
Mwalima Peltenburg
 
PDF
The Dom Scripting Toolkit J Query
QConLondon2008
 
Delivering a Responsive UI
Rebecca Murphey
 
Idioms in swift 2016 05c
Kaz Yoshikawa
 
Advanced jQuery
sergioafp
 
DOM Scripting Toolkit - jQuery
Remy Sharp
 
Beyond the DOM: Sane Structure for JS Apps
Rebecca Murphey
 
Javascript & jQuery: A pragmatic introduction
Iban Martinez
 
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기
Suyeol Jeon
 
Drupal csu-open atriumname
Emanuele Quinto
 
DataMapper @ RubyEnRails2009
Dirkjan Bussink
 
The Ring programming language version 1.5.2 book - Part 43 of 181
Mahmoud Samir Fayed
 
Rediscovering JavaScript: The Language Behind The Libraries
Simon Willison
 
Functionality Focused Code Organization
Rebecca Murphey
 
jQuery
Jay Poojara
 
Miniproject on Employee Management using Perl/Database.
Sanchit Raut
 
Elm: give it a try
Eugene Zharkov
 
画像Hacks
Yusuke Wada
 
Dig Deeper into WordPress - WD Meetup Cairo
Mohamed Mosaad
 
linieaire regressie
Mwalima Peltenburg
 
The Dom Scripting Toolkit J Query
QConLondon2008
 
Ad

Viewers also liked (7)

KEY
ScalaQuery
Trond Marius Øvstetun
 
PPT
En nybegynners introduksjon til scalaz
Trond Marius Øvstetun
 
PPTX
Gdg using docker to streamline development
Trond Marius Øvstetun
 
KEY
Persistens i scala
Trond Marius Øvstetun
 
PDF
The Near Future of CSS
Rachel Andrew
 
PDF
The Buyer's Journey - by Chris Lema
Chris Lema
 
PDF
The Presentation Come-Back Kid
Ethos3
 
En nybegynners introduksjon til scalaz
Trond Marius Øvstetun
 
Gdg using docker to streamline development
Trond Marius Øvstetun
 
Persistens i scala
Trond Marius Øvstetun
 
The Near Future of CSS
Rachel Andrew
 
The Buyer's Journey - by Chris Lema
Chris Lema
 
The Presentation Come-Back Kid
Ethos3
 
Ad

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

PDF
Scala ActiveRecord
scalaconfjp
 
PDF
Scala active record
鉄平 土佐
 
ODP
WorkingWithSlick2.1.0
Knoldus Inc.
 
PDF
Using Scala Slick at FortyTwo
Eishay Smith
 
PDF
Naver_alternative_to_jpa
NAVER Engineering
 
PDF
Software architecture2008 ejbql-quickref
jaiverlh
 
PPTX
Grails queries
Husain Dalal
 
PDF
Querydsl fin jug - june 2012
Timo Westkämper
 
PDF
Alternatives of JPA/Hibernate
Sunghyouk Bae
 
PDF
Querydsl overview 2014
Timo Westkämper
 
PDF
2012-08-29 - NoSQL Bootcamp (Redis, RavenDB & MongoDB für .NET Entwickler)
Johannes Hoppe
 
PDF
Requery overview
Sunghyouk Bae
 
PDF
springdatajpatwjug-120527215242-phpapp02.pdf
ssuser0562f1
 
PDF
greenDAO
Mu Chun Wang
 
PDF
ORMLite Android
哲偉 楊
 
PDF
Spring data requery
Sunghyouk Bae
 
PDF
ScalikeJDBC Tutorial for Beginners
Kazuhiro Sera
 
PPTX
DATABASE MANAGEMENT SYSTEM
Harshajajam
 
PPT
Introduction to hibernate
hr1383
 
PPT
Spring data
명철 강
 
Scala ActiveRecord
scalaconfjp
 
Scala active record
鉄平 土佐
 
WorkingWithSlick2.1.0
Knoldus Inc.
 
Using Scala Slick at FortyTwo
Eishay Smith
 
Naver_alternative_to_jpa
NAVER Engineering
 
Software architecture2008 ejbql-quickref
jaiverlh
 
Grails queries
Husain Dalal
 
Querydsl fin jug - june 2012
Timo Westkämper
 
Alternatives of JPA/Hibernate
Sunghyouk Bae
 
Querydsl overview 2014
Timo Westkämper
 
2012-08-29 - NoSQL Bootcamp (Redis, RavenDB & MongoDB für .NET Entwickler)
Johannes Hoppe
 
Requery overview
Sunghyouk Bae
 
springdatajpatwjug-120527215242-phpapp02.pdf
ssuser0562f1
 
greenDAO
Mu Chun Wang
 
ORMLite Android
哲偉 楊
 
Spring data requery
Sunghyouk Bae
 
ScalikeJDBC Tutorial for Beginners
Kazuhiro Sera
 
DATABASE MANAGEMENT SYSTEM
Harshajajam
 
Introduction to hibernate
hr1383
 
Spring data
명철 강
 

More from e-Legion (20)

PPTX
MBLT16: Elena Rydkina, Pure
e-Legion
 
PPTX
MBLT16: Alexander Lukin, AppMetrica
e-Legion
 
PPTX
MBLT16: Vincent Wu, Alibaba Mobile
e-Legion
 
PPTX
MBLT16: Dmitriy Geranin, Afisha Restorany
e-Legion
 
PPTX
MBLT16: Marvin Liao, 500Startups
e-Legion
 
PDF
MBLT16: Andrey Maslak, Aviasales
e-Legion
 
PDF
MBLT16: Andrey Bakalenko, Sberbank Online
e-Legion
 
PPTX
Rx Java architecture
e-Legion
 
PPTX
Rx java
e-Legion
 
PDF
MBLTDev15: Hector Zarate, Spotify
e-Legion
 
PDF
MBLTDev15: Cesar Valiente, Wunderlist
e-Legion
 
PDF
MBLTDev15: Brigit Lyons, Soundcloud
e-Legion
 
PDF
MBLTDev15: Egor Tolstoy, Rambler&Co
e-Legion
 
PDF
MBLTDev15: Alexander Orlov, Postforpost
e-Legion
 
PDF
MBLTDev15: Artemiy Sobolev, Parallels
e-Legion
 
PPTX
MBLTDev15: Alexander Dimchenko, DIT
e-Legion
 
PPTX
MBLTDev: Evgeny Lisovsky, Litres
e-Legion
 
PPTX
MBLTDev: Alexander Dimchenko, Bright Box
e-Legion
 
PPTX
MBLTDev15: Konstantin Goldshtein, Microsoft
e-Legion
 
PDF
MBLTDev15: Anna Mikhina, Maxim Evdokimov, Tinkoff Bank
e-Legion
 
MBLT16: Elena Rydkina, Pure
e-Legion
 
MBLT16: Alexander Lukin, AppMetrica
e-Legion
 
MBLT16: Vincent Wu, Alibaba Mobile
e-Legion
 
MBLT16: Dmitriy Geranin, Afisha Restorany
e-Legion
 
MBLT16: Marvin Liao, 500Startups
e-Legion
 
MBLT16: Andrey Maslak, Aviasales
e-Legion
 
MBLT16: Andrey Bakalenko, Sberbank Online
e-Legion
 
Rx Java architecture
e-Legion
 
Rx java
e-Legion
 
MBLTDev15: Hector Zarate, Spotify
e-Legion
 
MBLTDev15: Cesar Valiente, Wunderlist
e-Legion
 
MBLTDev15: Brigit Lyons, Soundcloud
e-Legion
 
MBLTDev15: Egor Tolstoy, Rambler&Co
e-Legion
 
MBLTDev15: Alexander Orlov, Postforpost
e-Legion
 
MBLTDev15: Artemiy Sobolev, Parallels
e-Legion
 
MBLTDev15: Alexander Dimchenko, DIT
e-Legion
 
MBLTDev: Evgeny Lisovsky, Litres
e-Legion
 
MBLTDev: Alexander Dimchenko, Bright Box
e-Legion
 
MBLTDev15: Konstantin Goldshtein, Microsoft
e-Legion
 
MBLTDev15: Anna Mikhina, Maxim Evdokimov, Tinkoff Bank
e-Legion
 

Recently uploaded (20)

PDF
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
PPTX
IoT Sensor Integration 2025 Powering Smart Tech and Industrial Automation.pptx
Rejig Digital
 
PDF
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
PDF
Advances in Ultra High Voltage (UHV) Transmission and Distribution Systems.pdf
Nabajyoti Banik
 
PDF
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
PDF
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
PDF
Software Development Methodologies in 2025
KodekX
 
PDF
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
PPTX
How to Build a Scalable Micro-Investing Platform in 2025 - A Founder’s Guide ...
Third Rock Techkno
 
PDF
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
PPTX
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
PDF
MASTERDECK GRAPHSUMMIT SYDNEY (Public).pdf
Neo4j
 
PDF
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
PPTX
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
PDF
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
PDF
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
PPT
Coupa-Kickoff-Meeting-Template presentai
annapureddyn
 
PDF
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
PDF
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
PDF
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
IoT Sensor Integration 2025 Powering Smart Tech and Industrial Automation.pptx
Rejig Digital
 
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
Advances in Ultra High Voltage (UHV) Transmission and Distribution Systems.pdf
Nabajyoti Banik
 
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
Software Development Methodologies in 2025
KodekX
 
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
How to Build a Scalable Micro-Investing Platform in 2025 - A Founder’s Guide ...
Third Rock Techkno
 
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
MASTERDECK GRAPHSUMMIT SYDNEY (Public).pdf
Neo4j
 
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
Coupa-Kickoff-Meeting-Template presentai
annapureddyn
 
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
Presentation about Hardware and Software in Computer
snehamodhawadiya
 

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

  • 1. SQUERYL ORM ! "#$%&#"#!'() $(*%) !"#$ %&'()* e-Legion Ltd., 2011 1
  • 2. ORM Query 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. ORM Query 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. 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. SQUERYL ORM SQL-+%,%-./0 DSL ,$1 23+4%!%& 564%731 6(+(23*(1 8#.9:# '%,3, -%$9:# ,#$3 5
  • 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. SQUERYL val olderThan20s = people.where(_.age gt 20) 7
  • 8. SQUERYL val olderThan20s = from (people) ( p => select (p) where (p.age gt 20) ) 8
  • 9. !"#!$% 9
  • 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. ,-(#*(.'&& 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. "/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 +%$#0 C%$1 )%7@6 -/69 var ($( val 8%B.% @'32369 432)#4, ()1 !6%$-*3 & -32# >3!$#,%&369 KeyedEntity .# %-1236#$9.% 13
  • 14. "/01( (CustomTypeMode) 5$%B./# '$3!!/ ,$1 +%$#0 8%7@6 &'$A"369 & !#-1 &3$(,3*(A, etc 14
  • 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.("#.(1 5&12( 15
  • 16. INSERT import MySchema._ val vasya = users.insert(new User("[email protected]", "Vasya")) users.insert(List(user1, user2)) 16
  • 17. SELECT from(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. FULL UPDATE //используем copy //поскольку все поля immutable val updatedVasya = vasya.copy(rating = vasya.rating + 1) users.update(updatedVasya) 18
  • 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. DELETE users.delete(1) val deleted = users.deleteWhere( u => u.rating.~ < 0 ) println("%s users deleted" format deleted) 20
  • 22. 2$&3(01"+ 2()450 5%!63&./# 23+4%!/ Group By ( 374#73*(1 Joins Relations 22
  • 23. COMPOSITE SELECT val rated = users.where( _.rating.~ >= 0) val vasyasRated = from(rated) ( u => select(u) where(u.name like “%Vasya%”) ) 23
  • 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. 067 SELECT C%!643.(".31 &/-%4'3 from(users) ( u => ... ).page(offset, pageLength) Distinct from(users) ( u => ... ).distinct ForUpdate from(users) ( u => ... ).forUpdate 25
  • 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. JOIN from(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. RELATIONS object 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. (STATELESS) RELATIONS case 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. STATEFUL RELATIONS case 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
  • 32. #02!",(,.& Compile-time Voodoo createEqualityExpressionWithLastAccessedFieldReferenceAndConstant >#6 UNION 5$(:'%) @)./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. $!8-!"%? 33
  • 34. "8("&9! email: [email protected] email: [email protected] www: http://digal.github.com/ twitter: @digal 34