SlideShare uma empresa Scribd logo
1 de 34
Baixar para ler offline
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

Mais conteúdo relacionado

Mais procurados

Delivering a Responsive UI
Delivering a Responsive UIDelivering a Responsive UI
Delivering a Responsive UI
Rebecca Murphey
 
Rediscovering JavaScript: The Language Behind The Libraries
Rediscovering JavaScript: The Language Behind The LibrariesRediscovering JavaScript: The Language Behind The Libraries
Rediscovering JavaScript: The Language Behind The Libraries
Simon Willison
 
The Dom Scripting Toolkit J Query
The Dom Scripting Toolkit J QueryThe Dom Scripting Toolkit J Query
The Dom Scripting Toolkit J Query
QConLondon2008
 

Mais procurados (20)

Delivering a Responsive UI
Delivering a Responsive UIDelivering a Responsive UI
Delivering a Responsive UI
 
Idioms in swift 2016 05c
Idioms in swift 2016 05cIdioms in swift 2016 05c
Idioms in swift 2016 05c
 
Advanced jQuery
Advanced jQueryAdvanced jQuery
Advanced jQuery
 
BVJS
BVJSBVJS
BVJS
 
DOM Scripting Toolkit - jQuery
DOM Scripting Toolkit - jQueryDOM Scripting Toolkit - jQuery
DOM Scripting Toolkit - jQuery
 
Beyond the DOM: Sane Structure for JS Apps
Beyond the DOM: Sane Structure for JS AppsBeyond the DOM: Sane Structure for JS Apps
Beyond the DOM: Sane Structure for JS Apps
 
Javascript & jQuery: A pragmatic introduction
Javascript & jQuery: A pragmatic introductionJavascript & jQuery: A pragmatic introduction
Javascript & jQuery: A pragmatic introduction
 
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기
 
Drupal csu-open atriumname
Drupal csu-open atriumnameDrupal csu-open atriumname
Drupal csu-open atriumname
 
DataMapper @ RubyEnRails2009
DataMapper @ RubyEnRails2009DataMapper @ RubyEnRails2009
DataMapper @ RubyEnRails2009
 
The Ring programming language version 1.5.2 book - Part 43 of 181
The Ring programming language version 1.5.2 book - Part 43 of 181The Ring programming language version 1.5.2 book - Part 43 of 181
The Ring programming language version 1.5.2 book - Part 43 of 181
 
Rediscovering JavaScript: The Language Behind The Libraries
Rediscovering JavaScript: The Language Behind The LibrariesRediscovering JavaScript: The Language Behind The Libraries
Rediscovering JavaScript: The Language Behind The Libraries
 
Functionality Focused Code Organization
Functionality Focused Code OrganizationFunctionality Focused Code Organization
Functionality Focused Code Organization
 
jQuery
jQueryjQuery
jQuery
 
Miniproject on Employee Management using Perl/Database.
Miniproject on Employee Management using Perl/Database.Miniproject on Employee Management using Perl/Database.
Miniproject on Employee Management using Perl/Database.
 
Elm: give it a try
Elm: give it a tryElm: give it a try
Elm: give it a try
 
画像Hacks
画像Hacks画像Hacks
画像Hacks
 
Dig Deeper into WordPress - WD Meetup Cairo
Dig Deeper into WordPress - WD Meetup CairoDig Deeper into WordPress - WD Meetup Cairo
Dig Deeper into WordPress - WD Meetup Cairo
 
linieaire regressie
linieaire regressielinieaire regressie
linieaire regressie
 
The Dom Scripting Toolkit J Query
The Dom Scripting Toolkit J QueryThe Dom Scripting Toolkit J Query
The Dom Scripting Toolkit J Query
 

Destaque (7)

ScalaQuery
ScalaQueryScalaQuery
ScalaQuery
 
En nybegynners introduksjon til scalaz
En nybegynners introduksjon til scalazEn nybegynners introduksjon til scalaz
En nybegynners introduksjon til scalaz
 
Gdg using docker to streamline development
Gdg using docker to streamline developmentGdg using docker to streamline development
Gdg using docker to streamline development
 
Persistens i scala
Persistens i scalaPersistens i scala
Persistens i scala
 
The Near Future of CSS
The Near Future of CSSThe Near Future of CSS
The Near Future of CSS
 
The Buyer's Journey - by Chris Lema
The Buyer's Journey - by Chris LemaThe Buyer's Journey - by Chris Lema
The Buyer's Journey - by Chris Lema
 
The Presentation Come-Back Kid
The Presentation Come-Back KidThe Presentation Come-Back Kid
The Presentation Come-Back Kid
 

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

前端MVC 豆瓣说
前端MVC 豆瓣说前端MVC 豆瓣说
前端MVC 豆瓣说
Ting Lv
 
Venturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
Venturing Into The Wild: A .NET Developer's Experience As A Ruby DeveloperVenturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
Venturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
Jon Kruger
 

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

The Ring programming language version 1.6 book - Part 46 of 189
The Ring programming language version 1.6 book - Part 46 of 189The Ring programming language version 1.6 book - Part 46 of 189
The Ring programming language version 1.6 book - Part 46 of 189
 
The Ring programming language version 1.3 book - Part 34 of 88
The Ring programming language version 1.3 book - Part 34 of 88The Ring programming language version 1.3 book - Part 34 of 88
The Ring programming language version 1.3 book - Part 34 of 88
 
The Ring programming language version 1.2 book - Part 32 of 84
The Ring programming language version 1.2 book - Part 32 of 84The Ring programming language version 1.2 book - Part 32 of 84
The Ring programming language version 1.2 book - Part 32 of 84
 
The Ring programming language version 1.5.4 book - Part 44 of 185
The Ring programming language version 1.5.4 book - Part 44 of 185The Ring programming language version 1.5.4 book - Part 44 of 185
The Ring programming language version 1.5.4 book - Part 44 of 185
 
Django - sql alchemy - jquery
Django - sql alchemy - jqueryDjango - sql alchemy - jquery
Django - sql alchemy - jquery
 
The Ring programming language version 1.5.3 book - Part 44 of 184
The Ring programming language version 1.5.3 book - Part 44 of 184The Ring programming language version 1.5.3 book - Part 44 of 184
The Ring programming language version 1.5.3 book - Part 44 of 184
 
The Ring programming language version 1.5.3 book - Part 54 of 184
The Ring programming language version 1.5.3 book - Part 54 of 184The Ring programming language version 1.5.3 book - Part 54 of 184
The Ring programming language version 1.5.3 book - Part 54 of 184
 
The Ring programming language version 1.10 book - Part 54 of 212
The Ring programming language version 1.10 book - Part 54 of 212The Ring programming language version 1.10 book - Part 54 of 212
The Ring programming language version 1.10 book - Part 54 of 212
 
Bag Of Tricks From Iusethis
Bag Of Tricks From IusethisBag Of Tricks From Iusethis
Bag Of Tricks From Iusethis
 
ScalikeJDBC Tutorial for Beginners
ScalikeJDBC Tutorial for BeginnersScalikeJDBC Tutorial for Beginners
ScalikeJDBC Tutorial for Beginners
 
JQuery Flot
JQuery FlotJQuery Flot
JQuery Flot
 
前端MVC 豆瓣说
前端MVC 豆瓣说前端MVC 豆瓣说
前端MVC 豆瓣说
 
Venturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
Venturing Into The Wild: A .NET Developer's Experience As A Ruby DeveloperVenturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
Venturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
 
Svcc 2013-d3
Svcc 2013-d3Svcc 2013-d3
Svcc 2013-d3
 
SVCC 2013 D3.js Presentation (10/05/2013)
SVCC 2013 D3.js Presentation (10/05/2013)SVCC 2013 D3.js Presentation (10/05/2013)
SVCC 2013 D3.js Presentation (10/05/2013)
 
The Ring programming language version 1.5.1 book - Part 42 of 180
The Ring programming language version 1.5.1 book - Part 42 of 180The Ring programming language version 1.5.1 book - Part 42 of 180
The Ring programming language version 1.5.1 book - Part 42 of 180
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ Etsy
 
The Ring programming language version 1.7 book - Part 48 of 196
The Ring programming language version 1.7 book - Part 48 of 196The Ring programming language version 1.7 book - Part 48 of 196
The Ring programming language version 1.7 book - Part 48 of 196
 
Tt subtemplates-caching
Tt subtemplates-cachingTt subtemplates-caching
Tt subtemplates-caching
 
Functional Principles for OO Developers
Functional Principles for OO DevelopersFunctional Principles for OO Developers
Functional Principles for OO Developers
 

Mais de e-Legion

Mais de e-Legion (20)

MBLT16: Elena Rydkina, Pure
MBLT16: Elena Rydkina, PureMBLT16: Elena Rydkina, Pure
MBLT16: Elena Rydkina, Pure
 
MBLT16: Alexander Lukin, AppMetrica
MBLT16: Alexander Lukin, AppMetricaMBLT16: Alexander Lukin, AppMetrica
MBLT16: Alexander Lukin, AppMetrica
 
MBLT16: Vincent Wu, Alibaba Mobile
MBLT16: Vincent Wu, Alibaba MobileMBLT16: Vincent Wu, Alibaba Mobile
MBLT16: Vincent Wu, Alibaba Mobile
 
MBLT16: Dmitriy Geranin, Afisha Restorany
MBLT16: Dmitriy Geranin, Afisha RestoranyMBLT16: Dmitriy Geranin, Afisha Restorany
MBLT16: Dmitriy Geranin, Afisha Restorany
 
MBLT16: Marvin Liao, 500Startups
MBLT16: Marvin Liao, 500StartupsMBLT16: Marvin Liao, 500Startups
MBLT16: Marvin Liao, 500Startups
 
MBLT16: Andrey Maslak, Aviasales
MBLT16: Andrey Maslak, AviasalesMBLT16: Andrey Maslak, Aviasales
MBLT16: Andrey Maslak, Aviasales
 
MBLT16: Andrey Bakalenko, Sberbank Online
MBLT16: Andrey Bakalenko, Sberbank OnlineMBLT16: Andrey Bakalenko, Sberbank Online
MBLT16: Andrey Bakalenko, Sberbank Online
 
Rx Java architecture
Rx Java architectureRx Java architecture
Rx Java architecture
 
Rx java
Rx javaRx java
Rx java
 
MBLTDev15: Hector Zarate, Spotify
MBLTDev15: Hector Zarate, SpotifyMBLTDev15: Hector Zarate, Spotify
MBLTDev15: Hector Zarate, Spotify
 
MBLTDev15: Cesar Valiente, Wunderlist
MBLTDev15: Cesar Valiente, WunderlistMBLTDev15: Cesar Valiente, Wunderlist
MBLTDev15: Cesar Valiente, Wunderlist
 
MBLTDev15: Brigit Lyons, Soundcloud
MBLTDev15: Brigit Lyons, SoundcloudMBLTDev15: Brigit Lyons, Soundcloud
MBLTDev15: Brigit Lyons, Soundcloud
 
MBLTDev15: Egor Tolstoy, Rambler&Co
MBLTDev15: Egor Tolstoy, Rambler&CoMBLTDev15: Egor Tolstoy, Rambler&Co
MBLTDev15: Egor Tolstoy, Rambler&Co
 
MBLTDev15: Alexander Orlov, Postforpost
MBLTDev15: Alexander Orlov, PostforpostMBLTDev15: Alexander Orlov, Postforpost
MBLTDev15: Alexander Orlov, Postforpost
 
MBLTDev15: Artemiy Sobolev, Parallels
MBLTDev15: Artemiy Sobolev, ParallelsMBLTDev15: Artemiy Sobolev, Parallels
MBLTDev15: Artemiy Sobolev, Parallels
 
MBLTDev15: Alexander Dimchenko, DIT
MBLTDev15: Alexander Dimchenko, DITMBLTDev15: Alexander Dimchenko, DIT
MBLTDev15: Alexander Dimchenko, DIT
 
MBLTDev: Evgeny Lisovsky, Litres
MBLTDev: Evgeny Lisovsky, LitresMBLTDev: Evgeny Lisovsky, Litres
MBLTDev: Evgeny Lisovsky, Litres
 
MBLTDev: Alexander Dimchenko, Bright Box
MBLTDev: Alexander Dimchenko, Bright Box MBLTDev: Alexander Dimchenko, Bright Box
MBLTDev: Alexander Dimchenko, Bright Box
 
MBLTDev15: Konstantin Goldshtein, Microsoft
MBLTDev15: Konstantin Goldshtein, MicrosoftMBLTDev15: Konstantin Goldshtein, Microsoft
MBLTDev15: Konstantin Goldshtein, Microsoft
 
MBLTDev15: Anna Mikhina, Maxim Evdokimov, Tinkoff Bank
MBLTDev15: Anna Mikhina, Maxim Evdokimov, Tinkoff Bank MBLTDev15: Anna Mikhina, Maxim Evdokimov, Tinkoff Bank
MBLTDev15: Anna Mikhina, Maxim Evdokimov, Tinkoff Bank
 

Último

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Último (20)

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 

Юрий Буянов «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("vasya@example.com", "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