SlideShare a Scribd company logo
1 of 28
Download to read offline
All your base are
belong to us
Pristup bazama podataka na Groovy
način

Dinko Srkoč, Helix d.o.o.
Groovy
● jezik s dinamičkim tipovima
● mogućnost statičke provjere tipova
● jednostavna integracija s Javom
● meta programiranje
● lagana izrada domenskih jezika (DSL)
● skripte
Groovy
@groovy.transform.ToString
class Osoba {
def ime
def prezime
}
def lista = 1..10
def osobe = lista.collect { i ->
new Osoba(ime: "Pero", prezime: "Perić the ${i}.")
}
println osobe[1]

// ispis: Osoba(Pero, Perić the 2.)
“

The JDBC™ API was designed to
keep simple things simple. This
means that the JDBC makes
everyday database tasks easy.

”
What happen ?

http://docs.oracle.com/javase/tutorial/jdbc/
JDBC

Java Database Connectivity

● komunikacija s bazom podataka ili drugim
tabličnim izvorom podataka
● neovisan o konkretnom sustavu za
upravljanje bazama podataka
● API za pristup bazi koristeći SQL

Somebody set us up the bomb.
JDBC

spajanje na bazu

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
public class Foo {
public static void main (String [] args) {
try {
Class.forName("org.h2.Driver");
Connection conn = DriverManager.getConnection("jdbc:h2:mem");
// ...
} catch (SQLException e) {
// ...
} catch (ClassNotFoundException e) {
// ...
}
}
}
JDBC

spajanje na bazu

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

// …
try {
Connection conn = dataSource.getConnection();
// ...
} catch (SQLException e) {
// ...
}

We get signal.
JDBC

dohvat podataka

import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
Statement stmt = conn.createStatement();
try {
ResultSet rs = stmt.executeQuery("SELECT col_a, col_b FROM a_table");
while (rs.next()) {
String colA = rs.getString("col_a");
int colB = rs.getInt("col_b");
// napraviti nešto s colA i colB ...
}
} catch (SQLException e) {
// ...
} finally {
stmt.close();
}
Ostalo (ORM, …)
● rješava problem upravljanja resursima
● nije potrebno pisati SQL za jednostavnije
slučajeve
● automatska pretvorba: ResultSet →POJO
ali
● izrada domain modela
● konfiguracija (XML, anotacije)
● često vlastiti jezik za složene upite
● dohvat više podataka nego što je potrebno
What !
Groovy

groovy.sql.Sql
groovy.sql.Sql

spajanje na bazu

import groovy.sql.Sql

def sql = Sql.newInstance('jdbc:h2:mem', 'org.h2.Driver')
// ili
def sql = new Sql(dataSource)

Main screen turn on.
groovy.sql.Sql

dohvat podataka

def sql = ...

sql.eachRow('SELECT col_a, col_b FROM a_table') { row -> // GroovyResultSet
row.col_a // napraviti nešto s col_a
row.col_b // i col_b
}
groovy.sql.Sql

dohvat podataka
[ meta-podaci ]

def sql = ...

def printColNames = { meta -> // ResultSetMetaData
(1..meta.columnCount).each {
print meta.getColumnLabel(it).padRight(20)
}
println()
}
sql.eachRow('SELECT * FROM a_table', printColNames) { row ->
row.toRowResult().values().each {
print it.toString().padRight(20)
}
println()
}

It’s you !!
groovy.sql.Sql

dohvat podataka
[ parametarski upit ]

def sql = ...

def limit = Date.from('yyyy-MM-dd', '2014-02-22')
sql.eachRow("SELECT * FROM a_table WHERE col_c < ?", [limit]) { row ->
// ...
}
groovy.sql.Sql

dohvat podataka
[ parametarski upit ]

def sql = ...

def namedParam = [limit: Date.from('yyyy-MM-dd', '2014-02-22')]
sql.eachRow("SELECT * FROM a_table WHERE col_a < :limit", namedParam) {
// ...
}

How are you gentlemen !!
groovy.sql.Sql

dohvat podataka
[ parametarski upit ]

def sql = ...

def limit = Date.from('yyyy-MM-dd', '2014-02-22')
sql.eachRow("SELECT * FROM a_table WHERE col_a < ${limit}") { row ->
// ...
}
groovy.sql.Sql

dohvat podataka
[ parametarski upit ]

def sql = ...

class LimitMe {
def limit
// ...
}
def limitObj = new LimitMe(limit: Date.from('yyyy-MM-dd', '2014-02-22'))
sql.eachRow("SELECT * FROM a_table WHERE col_a < :limit", limitObj) { row ->
// ...
}
You are on the way to destruction.
groovy.sql.Sql

dohvat podataka
[dohvat jednog sloga]

def sql = ...

def obj = sql.firstRow('SELECT * FROM a_table WHERE col_a = 1')
println obj.col_a + obj.col_b
groovy.sql.Sql

dohvat podataka
[ lista slogova ]

class Osoba {
def ime
def prezime
def mjesto_rodjenja
def god_rodjenja
}
sql.rows('SELECT mjesto_rodjenja, god_rodjenja FROM osobe').collect { row ->
new Osoba(row)
}.findAll { osoba ->
osoba.god_rodjenja > 1986 // zadnji prolaz Halleyevog kometa
}.groupBy { osoba ->
osoba.mjesto_rodjenja
}.collectEntries { mjesto, osobe ->
[mjesto, osobe.size()]
What you say !!
}
groovy.sql.Sql

def sql = ...

sql.execute '''
INSERT INTO a_table (col_a, col_b, col_c)
VALUES (?, ?, ?)
''', [42, 'foo', 'bar']

mijenjanje podataka
[ insert / update / ...]
groovy.sql.Sql

transakcije

def sql = ...

sql.withTransaction {
(1..100).each {
sql.execute("UPDATE a_table SET col_b = ${calc(it)} WHERE col_a = ${it}")
}
}

You have no chance to survive make your time.
groovy.sql.Sql

batch operacije

def sql = ...

sql.withTransaction {
sql.withBatch(30, 'INSERT INTO a_table VALUES (?, ?, ?)') { pstmt ->
sql.eachRow('SELECT * FROM b_table') { bTable ->
pstmt.addBatch(bTable.foo, bTable.bar, bTable.baz)
}
}
}
Groovy

groovy.sql.DataSet
groovy.sql.DataSet
class Osoba {
String ime
String prezime
String mjestoRodjenja
Integer godinaRodjenja
}
def osobe = new DataSet(sql, Osoba)
osobe.findAll {
it.godinaRodjenja > 1986
}.findAll {
it.mjestoRodjenja == 'Zagreb'
}.sort {
it.prezime
}.revert().rows()

sql.rows '''
SELECT * FROM osobe
WHERE godinarodjenja > 1986
AND mjestorodjenja = 'Zagreb'
ORDER BY prezime DESC
'''

You know what you doing.
Groovy

hr.helix.sqlstream.StreamingResultSet
StreamingResultSet

veliki skup podataka

def sql = ...

sql.withStream('SELECT * FROM the_world') { stream ->
stream.collect { row ->
new Osoba(row)
}.findAll { osoba ->
osoba.god_rodjenja > 1986
}.take(1000)
.toList()
}
Q
A
&

Hvala!
For great justice.

More Related Content

What's hot

Symfony2でMongoDBと仲良くする方法
Symfony2でMongoDBと仲良くする方法Symfony2でMongoDBと仲良くする方法
Symfony2でMongoDBと仲良くする方法Koji Iwazaki
 
Java Script - Object-Oriented Programming
Java Script - Object-Oriented ProgrammingJava Script - Object-Oriented Programming
Java Script - Object-Oriented Programmingintive
 
Simular un next del recordset en php de forma rudimentaria
Simular un next del recordset en php de forma rudimentariaSimular un next del recordset en php de forma rudimentaria
Simular un next del recordset en php de forma rudimentariajbersosa
 
Javascript and jQuery for Mobile
Javascript and jQuery for MobileJavascript and jQuery for Mobile
Javascript and jQuery for MobileIvano Malavolta
 
Sumahexavector
SumahexavectorSumahexavector
Sumahexavectorjbersosa
 
2017 - NoSQL Vorlesung Mosbach
2017 - NoSQL Vorlesung Mosbach2017 - NoSQL Vorlesung Mosbach
2017 - NoSQL Vorlesung MosbachJohannes Hoppe
 
Documentacion edderson callpa_ortiz
Documentacion edderson callpa_ortizDocumentacion edderson callpa_ortiz
Documentacion edderson callpa_ortizEdderson J. Ortiz
 
Javascript per applicazioni complesse - Lo Stretto digitale
Javascript per applicazioni complesse - Lo Stretto digitaleJavascript per applicazioni complesse - Lo Stretto digitale
Javascript per applicazioni complesse - Lo Stretto digitaleGiuseppe Pizzimenti
 
HTML5を使ったウェブアプリケーションの高速化
HTML5を使ったウェブアプリケーションの高速化HTML5を使ったウェブアプリケーションの高速化
HTML5を使ったウェブアプリケーションの高速化hagino 3000
 
Java весна 2013 лекция 7
Java весна 2013 лекция 7Java весна 2013 лекция 7
Java весна 2013 лекция 7Technopark
 
Assalamualaykum warahmatullahi wabarakatuu
Assalamualaykum warahmatullahi wabarakatuuAssalamualaykum warahmatullahi wabarakatuu
Assalamualaykum warahmatullahi wabarakatuuiswan_di
 
Decreto 054 atención al publico tempora semana santa 2
Decreto  054 atención al publico tempora semana santa 2Decreto  054 atención al publico tempora semana santa 2
Decreto 054 atención al publico tempora semana santa 2VIDEOS DE URABÁ
 

What's hot (20)

Symfony2でMongoDBと仲良くする方法
Symfony2でMongoDBと仲良くする方法Symfony2でMongoDBと仲良くする方法
Symfony2でMongoDBと仲良くする方法
 
Java Script - Object-Oriented Programming
Java Script - Object-Oriented ProgrammingJava Script - Object-Oriented Programming
Java Script - Object-Oriented Programming
 
Clase 10 electiva profesional 3 aws rds php y mysql
Clase 10 electiva profesional 3 aws rds php y mysqlClase 10 electiva profesional 3 aws rds php y mysql
Clase 10 electiva profesional 3 aws rds php y mysql
 
Simular un next del recordset en php de forma rudimentaria
Simular un next del recordset en php de forma rudimentariaSimular un next del recordset en php de forma rudimentaria
Simular un next del recordset en php de forma rudimentaria
 
Javascript and jQuery for Mobile
Javascript and jQuery for MobileJavascript and jQuery for Mobile
Javascript and jQuery for Mobile
 
Rubyslava2102
Rubyslava2102Rubyslava2102
Rubyslava2102
 
Phpex3
Phpex3Phpex3
Phpex3
 
Sumahexavector
SumahexavectorSumahexavector
Sumahexavector
 
Sumahex
SumahexSumahex
Sumahex
 
2017 - NoSQL Vorlesung Mosbach
2017 - NoSQL Vorlesung Mosbach2017 - NoSQL Vorlesung Mosbach
2017 - NoSQL Vorlesung Mosbach
 
Testování prakticky
Testování praktickyTestování prakticky
Testování prakticky
 
Documentacion edderson callpa_ortiz
Documentacion edderson callpa_ortizDocumentacion edderson callpa_ortiz
Documentacion edderson callpa_ortiz
 
Javascript per applicazioni complesse - Lo Stretto digitale
Javascript per applicazioni complesse - Lo Stretto digitaleJavascript per applicazioni complesse - Lo Stretto digitale
Javascript per applicazioni complesse - Lo Stretto digitale
 
HTML5を使ったウェブアプリケーションの高速化
HTML5を使ったウェブアプリケーションの高速化HTML5を使ったウェブアプリケーションの高速化
HTML5を使ったウェブアプリケーションの高速化
 
A z railphp v1.0
A z railphp v1.0A z railphp v1.0
A z railphp v1.0
 
Java весна 2013 лекция 7
Java весна 2013 лекция 7Java весна 2013 лекция 7
Java весна 2013 лекция 7
 
JQuery
JQueryJQuery
JQuery
 
Kruskal algorithm
Kruskal algorithmKruskal algorithm
Kruskal algorithm
 
Assalamualaykum warahmatullahi wabarakatuu
Assalamualaykum warahmatullahi wabarakatuuAssalamualaykum warahmatullahi wabarakatuu
Assalamualaykum warahmatullahi wabarakatuu
 
Decreto 054 atención al publico tempora semana santa 2
Decreto  054 atención al publico tempora semana santa 2Decreto  054 atención al publico tempora semana santa 2
Decreto 054 atención al publico tempora semana santa 2
 

Viewers also liked

Nemanja Čedomirović - PHP Srbija
Nemanja Čedomirović - PHP SrbijaNemanja Čedomirović - PHP Srbija
Nemanja Čedomirović - PHP SrbijaWebDan
 

Viewers also liked (11)

Javantura Zagreb 2014 - Nashorn - Miroslav Rešetar
Javantura Zagreb 2014 - Nashorn - Miroslav RešetarJavantura Zagreb 2014 - Nashorn - Miroslav Rešetar
Javantura Zagreb 2014 - Nashorn - Miroslav Rešetar
 
Javantura Zagreb 2014 - Sencha Touch - Denis Jajčević
Javantura Zagreb 2014 - Sencha Touch - Denis JajčevićJavantura Zagreb 2014 - Sencha Touch - Denis Jajčević
Javantura Zagreb 2014 - Sencha Touch - Denis Jajčević
 
Javantura Zagreb 2014 - Vert.x 1.3 - Mihovil Rister
Javantura Zagreb 2014 - Vert.x 1.3 - Mihovil RisterJavantura Zagreb 2014 - Vert.x 1.3 - Mihovil Rister
Javantura Zagreb 2014 - Vert.x 1.3 - Mihovil Rister
 
Javantura Zagreb 2014 - Google Dart - Željko Kunica
Javantura Zagreb 2014 - Google Dart - Željko KunicaJavantura Zagreb 2014 - Google Dart - Željko Kunica
Javantura Zagreb 2014 - Google Dart - Željko Kunica
 
HUJAK skupština 2014
HUJAK skupština 2014HUJAK skupština 2014
HUJAK skupština 2014
 
Javantura Zagreb 2014 - universAAL - Andrej Grgurić
Javantura Zagreb 2014 - universAAL - Andrej GrgurićJavantura Zagreb 2014 - universAAL - Andrej Grgurić
Javantura Zagreb 2014 - universAAL - Andrej Grgurić
 
Javantura Zagreb 2014 - WildFly 8 - Tomaž Cerar
Javantura Zagreb 2014 - WildFly 8 - Tomaž CerarJavantura Zagreb 2014 - WildFly 8 - Tomaž Cerar
Javantura Zagreb 2014 - WildFly 8 - Tomaž Cerar
 
Javantura Zagreb 2014 - Alfresco-Neo4j integracija - Damir Murat
Javantura Zagreb 2014 - Alfresco-Neo4j integracija - Damir MuratJavantura Zagreb 2014 - Alfresco-Neo4j integracija - Damir Murat
Javantura Zagreb 2014 - Alfresco-Neo4j integracija - Damir Murat
 
Javantura Zagreb 2014 - Java na klijenstskoj strani - Ivan Vučak
Javantura Zagreb 2014 - Java na klijenstskoj strani - Ivan VučakJavantura Zagreb 2014 - Java na klijenstskoj strani - Ivan Vučak
Javantura Zagreb 2014 - Java na klijenstskoj strani - Ivan Vučak
 
Javantura Zagreb 2014 - Vaadin - Peter Lehto
Javantura Zagreb 2014 - Vaadin - Peter LehtoJavantura Zagreb 2014 - Vaadin - Peter Lehto
Javantura Zagreb 2014 - Vaadin - Peter Lehto
 
Nemanja Čedomirović - PHP Srbija
Nemanja Čedomirović - PHP SrbijaNemanja Čedomirović - PHP Srbija
Nemanja Čedomirović - PHP Srbija
 

More from HUJAK - Hrvatska udruga Java korisnika / Croatian Java User Association

More from HUJAK - Hrvatska udruga Java korisnika / Croatian Java User Association (20)

Java cro'21 the best tools for java developers in 2021 - hujak
Java cro'21   the best tools for java developers in 2021 - hujakJava cro'21   the best tools for java developers in 2021 - hujak
Java cro'21 the best tools for java developers in 2021 - hujak
 
JavaCro'21 - Java is Here To Stay - HUJAK Keynote
JavaCro'21 - Java is Here To Stay - HUJAK KeynoteJavaCro'21 - Java is Here To Stay - HUJAK Keynote
JavaCro'21 - Java is Here To Stay - HUJAK Keynote
 
Javantura v7 - Behaviour Driven Development with Cucumber - Ivan Lozić
Javantura v7 - Behaviour Driven Development with Cucumber - Ivan LozićJavantura v7 - Behaviour Driven Development with Cucumber - Ivan Lozić
Javantura v7 - Behaviour Driven Development with Cucumber - Ivan Lozić
 
Javantura v7 - The State of Java - Today and Tomowwow - HUJAK's Community Key...
Javantura v7 - The State of Java - Today and Tomowwow - HUJAK's Community Key...Javantura v7 - The State of Java - Today and Tomowwow - HUJAK's Community Key...
Javantura v7 - The State of Java - Today and Tomowwow - HUJAK's Community Key...
 
Javantura v7 - Learning to Scale Yourself: The Journey from Coder to Leader -...
Javantura v7 - Learning to Scale Yourself: The Journey from Coder to Leader -...Javantura v7 - Learning to Scale Yourself: The Journey from Coder to Leader -...
Javantura v7 - Learning to Scale Yourself: The Journey from Coder to Leader -...
 
JavaCro'19 - The State of Java and Software Development in Croatia - Communit...
JavaCro'19 - The State of Java and Software Development in Croatia - Communit...JavaCro'19 - The State of Java and Software Development in Croatia - Communit...
JavaCro'19 - The State of Java and Software Development in Croatia - Communit...
 
Javantura v6 - Java in Croatia and HUJAK - Branko Mihaljević, Aleksander Radovan
Javantura v6 - Java in Croatia and HUJAK - Branko Mihaljević, Aleksander RadovanJavantura v6 - Java in Croatia and HUJAK - Branko Mihaljević, Aleksander Radovan
Javantura v6 - Java in Croatia and HUJAK - Branko Mihaljević, Aleksander Radovan
 
Javantura v6 - On the Aspects of Polyglot Programming and Memory Management i...
Javantura v6 - On the Aspects of Polyglot Programming and Memory Management i...Javantura v6 - On the Aspects of Polyglot Programming and Memory Management i...
Javantura v6 - On the Aspects of Polyglot Programming and Memory Management i...
 
Javantura v6 - Case Study: Marketplace App with Java and Hyperledger Fabric -...
Javantura v6 - Case Study: Marketplace App with Java and Hyperledger Fabric -...Javantura v6 - Case Study: Marketplace App with Java and Hyperledger Fabric -...
Javantura v6 - Case Study: Marketplace App with Java and Hyperledger Fabric -...
 
Javantura v6 - How to help customers report bugs accurately - Miroslav Čerkez...
Javantura v6 - How to help customers report bugs accurately - Miroslav Čerkez...Javantura v6 - How to help customers report bugs accurately - Miroslav Čerkez...
Javantura v6 - How to help customers report bugs accurately - Miroslav Čerkez...
 
Javantura v6 - When remote work really works - the secrets behind successful ...
Javantura v6 - When remote work really works - the secrets behind successful ...Javantura v6 - When remote work really works - the secrets behind successful ...
Javantura v6 - When remote work really works - the secrets behind successful ...
 
Javantura v6 - Kotlin-Java Interop - Matej Vidaković
Javantura v6 - Kotlin-Java Interop - Matej VidakovićJavantura v6 - Kotlin-Java Interop - Matej Vidaković
Javantura v6 - Kotlin-Java Interop - Matej Vidaković
 
Javantura v6 - Spring HATEOAS hypermedia-driven web services, and clients tha...
Javantura v6 - Spring HATEOAS hypermedia-driven web services, and clients tha...Javantura v6 - Spring HATEOAS hypermedia-driven web services, and clients tha...
Javantura v6 - Spring HATEOAS hypermedia-driven web services, and clients tha...
 
Javantura v6 - End to End Continuous Delivery of Microservices for Kubernetes...
Javantura v6 - End to End Continuous Delivery of Microservices for Kubernetes...Javantura v6 - End to End Continuous Delivery of Microservices for Kubernetes...
Javantura v6 - End to End Continuous Delivery of Microservices for Kubernetes...
 
Javantura v6 - Istio Service Mesh - The magic between your microservices - Ma...
Javantura v6 - Istio Service Mesh - The magic between your microservices - Ma...Javantura v6 - Istio Service Mesh - The magic between your microservices - Ma...
Javantura v6 - Istio Service Mesh - The magic between your microservices - Ma...
 
Javantura v6 - How can you improve the quality of your application - Ioannis ...
Javantura v6 - How can you improve the quality of your application - Ioannis ...Javantura v6 - How can you improve the quality of your application - Ioannis ...
Javantura v6 - How can you improve the quality of your application - Ioannis ...
 
Javantura v6 - Just say it v2 - Pavao Varela Petrac
Javantura v6 - Just say it v2 - Pavao Varela PetracJavantura v6 - Just say it v2 - Pavao Varela Petrac
Javantura v6 - Just say it v2 - Pavao Varela Petrac
 
Javantura v6 - Automation of web apps testing - Hrvoje Ruhek
Javantura v6 - Automation of web apps testing - Hrvoje RuhekJavantura v6 - Automation of web apps testing - Hrvoje Ruhek
Javantura v6 - Automation of web apps testing - Hrvoje Ruhek
 
Javantura v6 - Master the Concepts Behind the Java 10 Challenges and Eliminat...
Javantura v6 - Master the Concepts Behind the Java 10 Challenges and Eliminat...Javantura v6 - Master the Concepts Behind the Java 10 Challenges and Eliminat...
Javantura v6 - Master the Concepts Behind the Java 10 Challenges and Eliminat...
 
Javantura v6 - Building IoT Middleware with Microservices - Mario Kusek
Javantura v6 - Building IoT Middleware with Microservices - Mario KusekJavantura v6 - Building IoT Middleware with Microservices - Mario Kusek
Javantura v6 - Building IoT Middleware with Microservices - Mario Kusek
 

Javantura Zagreb 2014 - Groovy-SQL - Dinko Srkoč

  • 1. All your base are belong to us Pristup bazama podataka na Groovy način Dinko Srkoč, Helix d.o.o.
  • 2.
  • 3. Groovy ● jezik s dinamičkim tipovima ● mogućnost statičke provjere tipova ● jednostavna integracija s Javom ● meta programiranje ● lagana izrada domenskih jezika (DSL) ● skripte
  • 4. Groovy @groovy.transform.ToString class Osoba { def ime def prezime } def lista = 1..10 def osobe = lista.collect { i -> new Osoba(ime: "Pero", prezime: "Perić the ${i}.") } println osobe[1] // ispis: Osoba(Pero, Perić the 2.)
  • 5. “ The JDBC™ API was designed to keep simple things simple. This means that the JDBC makes everyday database tasks easy. ” What happen ? http://docs.oracle.com/javase/tutorial/jdbc/
  • 6. JDBC Java Database Connectivity ● komunikacija s bazom podataka ili drugim tabličnim izvorom podataka ● neovisan o konkretnom sustavu za upravljanje bazama podataka ● API za pristup bazi koristeći SQL Somebody set us up the bomb.
  • 7. JDBC spajanje na bazu import java.sql.DriverManager; import java.sql.Connection; import java.sql.SQLException; public class Foo { public static void main (String [] args) { try { Class.forName("org.h2.Driver"); Connection conn = DriverManager.getConnection("jdbc:h2:mem"); // ... } catch (SQLException e) { // ... } catch (ClassNotFoundException e) { // ... } } }
  • 8. JDBC spajanje na bazu import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; // … try { Connection conn = dataSource.getConnection(); // ... } catch (SQLException e) { // ... } We get signal.
  • 9. JDBC dohvat podataka import java.sql.Statement; import java.sql.ResultSet; import java.sql.SQLException; Statement stmt = conn.createStatement(); try { ResultSet rs = stmt.executeQuery("SELECT col_a, col_b FROM a_table"); while (rs.next()) { String colA = rs.getString("col_a"); int colB = rs.getInt("col_b"); // napraviti nešto s colA i colB ... } } catch (SQLException e) { // ... } finally { stmt.close(); }
  • 10. Ostalo (ORM, …) ● rješava problem upravljanja resursima ● nije potrebno pisati SQL za jednostavnije slučajeve ● automatska pretvorba: ResultSet →POJO ali ● izrada domain modela ● konfiguracija (XML, anotacije) ● često vlastiti jezik za složene upite ● dohvat više podataka nego što je potrebno What !
  • 12. groovy.sql.Sql spajanje na bazu import groovy.sql.Sql def sql = Sql.newInstance('jdbc:h2:mem', 'org.h2.Driver') // ili def sql = new Sql(dataSource) Main screen turn on.
  • 13. groovy.sql.Sql dohvat podataka def sql = ... sql.eachRow('SELECT col_a, col_b FROM a_table') { row -> // GroovyResultSet row.col_a // napraviti nešto s col_a row.col_b // i col_b }
  • 14. groovy.sql.Sql dohvat podataka [ meta-podaci ] def sql = ... def printColNames = { meta -> // ResultSetMetaData (1..meta.columnCount).each { print meta.getColumnLabel(it).padRight(20) } println() } sql.eachRow('SELECT * FROM a_table', printColNames) { row -> row.toRowResult().values().each { print it.toString().padRight(20) } println() } It’s you !!
  • 15. groovy.sql.Sql dohvat podataka [ parametarski upit ] def sql = ... def limit = Date.from('yyyy-MM-dd', '2014-02-22') sql.eachRow("SELECT * FROM a_table WHERE col_c < ?", [limit]) { row -> // ... }
  • 16. groovy.sql.Sql dohvat podataka [ parametarski upit ] def sql = ... def namedParam = [limit: Date.from('yyyy-MM-dd', '2014-02-22')] sql.eachRow("SELECT * FROM a_table WHERE col_a < :limit", namedParam) { // ... } How are you gentlemen !!
  • 17. groovy.sql.Sql dohvat podataka [ parametarski upit ] def sql = ... def limit = Date.from('yyyy-MM-dd', '2014-02-22') sql.eachRow("SELECT * FROM a_table WHERE col_a < ${limit}") { row -> // ... }
  • 18. groovy.sql.Sql dohvat podataka [ parametarski upit ] def sql = ... class LimitMe { def limit // ... } def limitObj = new LimitMe(limit: Date.from('yyyy-MM-dd', '2014-02-22')) sql.eachRow("SELECT * FROM a_table WHERE col_a < :limit", limitObj) { row -> // ... } You are on the way to destruction.
  • 19. groovy.sql.Sql dohvat podataka [dohvat jednog sloga] def sql = ... def obj = sql.firstRow('SELECT * FROM a_table WHERE col_a = 1') println obj.col_a + obj.col_b
  • 20. groovy.sql.Sql dohvat podataka [ lista slogova ] class Osoba { def ime def prezime def mjesto_rodjenja def god_rodjenja } sql.rows('SELECT mjesto_rodjenja, god_rodjenja FROM osobe').collect { row -> new Osoba(row) }.findAll { osoba -> osoba.god_rodjenja > 1986 // zadnji prolaz Halleyevog kometa }.groupBy { osoba -> osoba.mjesto_rodjenja }.collectEntries { mjesto, osobe -> [mjesto, osobe.size()] What you say !! }
  • 21. groovy.sql.Sql def sql = ... sql.execute ''' INSERT INTO a_table (col_a, col_b, col_c) VALUES (?, ?, ?) ''', [42, 'foo', 'bar'] mijenjanje podataka [ insert / update / ...]
  • 22. groovy.sql.Sql transakcije def sql = ... sql.withTransaction { (1..100).each { sql.execute("UPDATE a_table SET col_b = ${calc(it)} WHERE col_a = ${it}") } } You have no chance to survive make your time.
  • 23. groovy.sql.Sql batch operacije def sql = ... sql.withTransaction { sql.withBatch(30, 'INSERT INTO a_table VALUES (?, ?, ?)') { pstmt -> sql.eachRow('SELECT * FROM b_table') { bTable -> pstmt.addBatch(bTable.foo, bTable.bar, bTable.baz) } } }
  • 25. groovy.sql.DataSet class Osoba { String ime String prezime String mjestoRodjenja Integer godinaRodjenja } def osobe = new DataSet(sql, Osoba) osobe.findAll { it.godinaRodjenja > 1986 }.findAll { it.mjestoRodjenja == 'Zagreb' }.sort { it.prezime }.revert().rows() sql.rows ''' SELECT * FROM osobe WHERE godinarodjenja > 1986 AND mjestorodjenja = 'Zagreb' ORDER BY prezime DESC ''' You know what you doing.
  • 27. StreamingResultSet veliki skup podataka def sql = ... sql.withStream('SELECT * FROM the_world') { stream -> stream.collect { row -> new Osoba(row) }.findAll { osoba -> osoba.god_rodjenja > 1986 }.take(1000) .toList() }