SlideShare uma empresa Scribd logo
1 de 31
Baixar para ler offline
jOOQ
SQL orientado a objetos
The Developers Conference
São Paulo - 2016
Gabriel Saraiva
Desenvolvedor na
SQL ❤
String sql = "SELECT * FROM users WHERE email = ?";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1,"example@xyz.com");
SQL ❤ ?
String sql = "UPDATE products" +
"SET name = ?, ..., price = ?" +
"WHERE id = ?";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, "Café");
// 98 campos depois...
stmt.setLong(99, 123L);
(╯°□°)╯︵ ┻━┻
String sql = "SELECT avg(age), cityId " +
"FROM users " +
(filter ? "WHERE cityId IN (...) ":"") +
"GROUP BY cityId " +
(order ? "ORDER BY name DESC":"") +
...
;
SQL !!!
SQL:
“Stringish Query Langage” ?
SQL = Structured Query Language
O problema não é o SQL.
É como escrevemos SQL.
SQL ❤ !!!
String sql = select()
.from(USERS)
.where(
USERS.ID.in(ids)
)
.toString();
“The easiest way to write SQL in Java”
or in
Scala
jOOQ:
Uma DSL para
escrever SQL
Setup:
1 minuto.
Setup:
1 minuto.
<dependency>
<groupId>org.jooq</groupId>
<artifactId>jooq</artifactId>
<version>3.8.2</version>
</dependency>
<dependency>
<groupId>org.jooq</groupId>
<artifactId>jooq-meta</artifactId>
<version>3.8.2</version>
</dependency>
<dependency>
<groupId>org.jooq</groupId>
<artifactId>jooq-
codegen</artifactId>
<version>3.8.2</version>
</dependency>
Setup:
1 minuto
ou mais!
Type Safe
select()
.from(USERS)
.where(
USERS.EMAIL.equal(1234)
)
Sintaxe
Fluente
select()
.from(USERS)
.where(
USERS.ID.equal(1234),
USERS.AGE.equal(26)
)
SQL
Injection
Safe
String name =
"Bob"); DROP TABLE users; --";
select()
.from(USERS)
.where(
USERS.NAME.eq(name)
)
Free:
p/ bancos
Open Source
$$$:
p/ bancos
Enterprise
mais informações disponíveis em: http://www.jooq.
org/legal/licensing#databases
Modelo
do Banco:
(opcional)
Automático!
<configuration>
<jdbc>
<driver>com.mysql.jdbc.Driver</driver>
<url>jdbc:mysql://localhost:3306</url>
<user>root</user>
<password>password</password>
</jdbc>
<generator>
<database>
<name>org.jooq.util.mysql.MySQLDatabase</name>
<includes>.*</includes>
<excludes/>
<inputSchema>example_database</inputSchema>
<unsignedTypes>false</unsignedTypes>
</database>
<target>
<packageName>com.example.database</packageName>
<directory>src/main/java</directory>
</target>
</generator>
</configuration>
Usando o jOOQ para
escrever SQL
1 minuto de setup: Sem modelo do db.
String sql = DSL.using(SQLDialect.MYSQL)
.select(field("name"), field("phone"))
.from("users")
.where(
field("id").equal(1234)
)
.toString();
2 minutos de setup: Modelo db automático
String sql = select(USERS.NAME, USERS.PHONE)
.from(USERS)
.where(
USERS.ID.eq(1234L)
)
.toString();
Inserts sem
?,?,?,?,?,?,,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?
,?,? será que faltou um ?
String sql = insertInto(USERS)
.set(USERS.NAME,"Gabriel Saraiva")
.set(USERS.PHONE,"16999666333")
.set(USERS.EMAIL,"gabrielsaraiva7@gmail.com")
.toString();
Filtros
String sql = select()
.from(PRODUCTS)
.where(PRODUCTS.CATEGORY.eq("drinks")
.or(PRODUCTS.CATEGORY.eq("beers"))
.and(PRODUCTS.NAME.contains("coffee"))
)
.toString();
Lista de Filtros
List<Condition> filters = Arrays.asList(
PRODUCTS.CATEGORY.equal("drinks"),
PRODUCTS.PRICE.greaterThan(new BigDecimal(25))
);
String sql = select(PRODUCTS.NAME, PRODUCTS.PRICE)
.from(PRODUCTS)
.where(filters)
.orderBy(PRODUCTS.PRICE.desc())
.toString();
Joins!
Users u = USERS;
Orders o = ORDERS;
OrdersProducts op = ORDERS_PRODUCTS;
Products p = PRODUCTS;
String sql = select()
.from(u
.innerJoin(o).on(u.ID.eq(o.USER_ID))
.innerJoin(op).on(o.ID.eq(op.ORDER_ID))
.innerJoin(p).on(p.ID.eq(op.ORDER_ID))
)
.toString();
Group By!
String sql = DSL.
select(
u.NAME,
o.ID,
sum(op.PRODUCT_SOLD_PRICE)
)
.from(join)
.where(filters)
.groupBy(o.ID)
.toString();
Lendo dados do ResultSet
ResultSet rs = stmt.executeQuery();
rs.next();
return new Product(
rs.getLong(PRODUCTS.ID.getName()),
rs.getString(PRODUCTS.NAME.getName()),
rs.getBigDecimal(PRODUCTS.PRICE.getName()),
rs.getString(PRODUCTS.CATEGORY.getName())
);
Escrever SQL
pode ser
divertido!
Obrigado
Gabriel Saraiva
gabriel.saraiva7@gmail.com
github.com/gabrsar
twitter/gabrielSaraivaAgradecimentos ❤
Igor Escobar
Giuliano Caliari
Diego Leme

Mais conteúdo relacionado

Destaque

An introduction to Reactive applications, Reactive Streams, and options for t...
An introduction to Reactive applications, Reactive Streams, and options for t...An introduction to Reactive applications, Reactive Streams, and options for t...
An introduction to Reactive applications, Reactive Streams, and options for t...
Steve Pember
 

Destaque (8)

openEHR: NHS Code4Health RippleOSI and EtherCis
openEHR: NHS Code4Health RippleOSI and EtherCisopenEHR: NHS Code4Health RippleOSI and EtherCis
openEHR: NHS Code4Health RippleOSI and EtherCis
 
jOOQ at Topconf 2013
jOOQ at Topconf 2013jOOQ at Topconf 2013
jOOQ at Topconf 2013
 
ORM is an Offensive Anti-Pattern
ORM is an Offensive Anti-PatternORM is an Offensive Anti-Pattern
ORM is an Offensive Anti-Pattern
 
An Introduction to jOOQ
An Introduction to jOOQAn Introduction to jOOQ
An Introduction to jOOQ
 
An introduction to Reactive applications, Reactive Streams, and options for t...
An introduction to Reactive applications, Reactive Streams, and options for t...An introduction to Reactive applications, Reactive Streams, and options for t...
An introduction to Reactive applications, Reactive Streams, and options for t...
 
jooqってなんて読むの? から始めるO/RマッパーとSpringBootの世界
jooqってなんて読むの? から始めるO/RマッパーとSpringBootの世界jooqってなんて読むの? から始めるO/RマッパーとSpringBootの世界
jooqってなんて読むの? から始めるO/RマッパーとSpringBootの世界
 
Reactive Streams and the Wide World of Groovy
Reactive Streams and the Wide World of GroovyReactive Streams and the Wide World of Groovy
Reactive Streams and the Wide World of Groovy
 
openEHR Technical Workshop Intro MIE 2016
openEHR Technical Workshop Intro MIE 2016openEHR Technical Workshop Intro MIE 2016
openEHR Technical Workshop Intro MIE 2016
 

Semelhante a TDC2016SP - JooQ: SQL orientado a objetos.

Юрий Буянов «Squeryl — ORM с человеческим лицом»
Юрий Буянов «Squeryl — ORM с человеческим лицом»Юрий Буянов «Squeryl — ORM с человеческим лицом»
Юрий Буянов «Squeryl — ORM с человеческим лицом»
e-Legion
 
Running Intelligent Applications inside a Database: Deep Learning with Python...
Running Intelligent Applications inside a Database: Deep Learning with Python...Running Intelligent Applications inside a Database: Deep Learning with Python...
Running Intelligent Applications inside a Database: Deep Learning with Python...
Miguel González-Fierro
 
Viki Big Data Meetup 2013_10
Viki Big Data Meetup 2013_10Viki Big Data Meetup 2013_10
Viki Big Data Meetup 2013_10
ishanagrawal90
 

Semelhante a TDC2016SP - JooQ: SQL orientado a objetos. (20)

code for quiz in my sql
code for quiz  in my sql code for quiz  in my sql
code for quiz in my sql
 
jQuery Foot-Gun Features
jQuery Foot-Gun FeaturesjQuery Foot-Gun Features
jQuery Foot-Gun Features
 
greenDAO
greenDAOgreenDAO
greenDAO
 
Programming with Python and PostgreSQL
Programming with Python and PostgreSQLProgramming with Python and PostgreSQL
Programming with Python and PostgreSQL
 
Svcc 2013-d3
Svcc 2013-d3Svcc 2013-d3
Svcc 2013-d3
 
Юрий Буянов «Squeryl — ORM с человеческим лицом»
Юрий Буянов «Squeryl — ORM с человеческим лицом»Юрий Буянов «Squeryl — ORM с человеческим лицом»
Юрий Буянов «Squeryl — ORM с человеческим лицом»
 
Running Intelligent Applications inside a Database: Deep Learning with Python...
Running Intelligent Applications inside a Database: Deep Learning with Python...Running Intelligent Applications inside a Database: Deep Learning with Python...
Running Intelligent Applications inside a Database: Deep Learning with Python...
 
mobl
moblmobl
mobl
 
goto java; (Jfokus)
goto java; (Jfokus)goto java; (Jfokus)
goto java; (Jfokus)
 
Advance java
Advance javaAdvance java
Advance java
 
Informatica_MDM_User_Exits.ppt
Informatica_MDM_User_Exits.pptInformatica_MDM_User_Exits.ppt
Informatica_MDM_User_Exits.ppt
 
JavaTalks: OOD principles
JavaTalks: OOD principlesJavaTalks: OOD principles
JavaTalks: OOD principles
 
#ITsubbotnik Spring 2017: Roman Iovlev "Java edge in test automation"
#ITsubbotnik Spring 2017: Roman Iovlev "Java edge in test automation"#ITsubbotnik Spring 2017: Roman Iovlev "Java edge in test automation"
#ITsubbotnik Spring 2017: Roman Iovlev "Java edge in test automation"
 
C#7, 7.1, 7.2, 7.3 e C# 8
C#7, 7.1, 7.2, 7.3 e C# 8C#7, 7.1, 7.2, 7.3 e C# 8
C#7, 7.1, 7.2, 7.3 e C# 8
 
The rise of json in rdbms land jab17
The rise of json in rdbms land jab17The rise of json in rdbms land jab17
The rise of json in rdbms land jab17
 
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
 
Viki Big Data Meetup 2013_10
Viki Big Data Meetup 2013_10Viki Big Data Meetup 2013_10
Viki Big Data Meetup 2013_10
 
NoSQL meets Microservices - Michael Hackstein
NoSQL meets Microservices - Michael HacksteinNoSQL meets Microservices - Michael Hackstein
NoSQL meets Microservices - Michael Hackstein
 
A la découverte de TypeScript
A la découverte de TypeScriptA la découverte de TypeScript
A la découverte de TypeScript
 
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
 

Mais de tdc-globalcode

Mais de tdc-globalcode (20)

TDC2019 Intel Software Day - Visao Computacional e IA a servico da humanidade
TDC2019 Intel Software Day - Visao Computacional e IA a servico da humanidadeTDC2019 Intel Software Day - Visao Computacional e IA a servico da humanidade
TDC2019 Intel Software Day - Visao Computacional e IA a servico da humanidade
 
TDC2019 Intel Software Day - Tecnicas de Programacao Paralela em Machine Lear...
TDC2019 Intel Software Day - Tecnicas de Programacao Paralela em Machine Lear...TDC2019 Intel Software Day - Tecnicas de Programacao Paralela em Machine Lear...
TDC2019 Intel Software Day - Tecnicas de Programacao Paralela em Machine Lear...
 
TDC2019 Intel Software Day - ACATE - Cases de Sucesso
TDC2019 Intel Software Day - ACATE - Cases de SucessoTDC2019 Intel Software Day - ACATE - Cases de Sucesso
TDC2019 Intel Software Day - ACATE - Cases de Sucesso
 
TDC2019 Intel Software Day - Otimizacao grafica com o Intel GPA
TDC2019 Intel Software Day - Otimizacao grafica com o Intel GPATDC2019 Intel Software Day - Otimizacao grafica com o Intel GPA
TDC2019 Intel Software Day - Otimizacao grafica com o Intel GPA
 
TDC2019 Intel Software Day - Deteccao de objetos em tempo real com OpenVino
TDC2019 Intel Software Day - Deteccao de objetos em tempo real com OpenVinoTDC2019 Intel Software Day - Deteccao de objetos em tempo real com OpenVino
TDC2019 Intel Software Day - Deteccao de objetos em tempo real com OpenVino
 
TDC2019 Intel Software Day - OpenCV: Inteligencia artificial e Visao Computac...
TDC2019 Intel Software Day - OpenCV: Inteligencia artificial e Visao Computac...TDC2019 Intel Software Day - OpenCV: Inteligencia artificial e Visao Computac...
TDC2019 Intel Software Day - OpenCV: Inteligencia artificial e Visao Computac...
 
TDC2019 Intel Software Day - Inferencia de IA em edge devices
TDC2019 Intel Software Day - Inferencia de IA em edge devicesTDC2019 Intel Software Day - Inferencia de IA em edge devices
TDC2019 Intel Software Day - Inferencia de IA em edge devices
 
Trilha BigData - Banco de Dados Orientado a Grafos na Seguranca Publica
Trilha BigData - Banco de Dados Orientado a Grafos na Seguranca PublicaTrilha BigData - Banco de Dados Orientado a Grafos na Seguranca Publica
Trilha BigData - Banco de Dados Orientado a Grafos na Seguranca Publica
 
Trilha .Net - Programacao funcional usando f#
Trilha .Net - Programacao funcional usando f#Trilha .Net - Programacao funcional usando f#
Trilha .Net - Programacao funcional usando f#
 
TDC2018SP | Trilha Go - Case Easylocus
TDC2018SP | Trilha Go - Case EasylocusTDC2018SP | Trilha Go - Case Easylocus
TDC2018SP | Trilha Go - Case Easylocus
 
TDC2018SP | Trilha Modern Web - Para onde caminha a Web?
TDC2018SP | Trilha Modern Web - Para onde caminha a Web?TDC2018SP | Trilha Modern Web - Para onde caminha a Web?
TDC2018SP | Trilha Modern Web - Para onde caminha a Web?
 
TDC2018SP | Trilha Go - Clean architecture em Golang
TDC2018SP | Trilha Go - Clean architecture em GolangTDC2018SP | Trilha Go - Clean architecture em Golang
TDC2018SP | Trilha Go - Clean architecture em Golang
 
TDC2018SP | Trilha Go - "Go" tambem e linguagem de QA
TDC2018SP | Trilha Go - "Go" tambem e linguagem de QATDC2018SP | Trilha Go - "Go" tambem e linguagem de QA
TDC2018SP | Trilha Go - "Go" tambem e linguagem de QA
 
TDC2018SP | Trilha Mobile - Digital Wallets - Seguranca, inovacao e tendencia
TDC2018SP | Trilha Mobile - Digital Wallets - Seguranca, inovacao e tendenciaTDC2018SP | Trilha Mobile - Digital Wallets - Seguranca, inovacao e tendencia
TDC2018SP | Trilha Mobile - Digital Wallets - Seguranca, inovacao e tendencia
 
TDC2018SP | Trilha .Net - Real Time apps com Azure SignalR Service
TDC2018SP | Trilha .Net - Real Time apps com Azure SignalR ServiceTDC2018SP | Trilha .Net - Real Time apps com Azure SignalR Service
TDC2018SP | Trilha .Net - Real Time apps com Azure SignalR Service
 
TDC2018SP | Trilha .Net - Passado, Presente e Futuro do .NET
TDC2018SP | Trilha .Net - Passado, Presente e Futuro do .NETTDC2018SP | Trilha .Net - Passado, Presente e Futuro do .NET
TDC2018SP | Trilha .Net - Passado, Presente e Futuro do .NET
 
TDC2018SP | Trilha .Net - Novidades do C# 7 e 8
TDC2018SP | Trilha .Net - Novidades do C# 7 e 8TDC2018SP | Trilha .Net - Novidades do C# 7 e 8
TDC2018SP | Trilha .Net - Novidades do C# 7 e 8
 
TDC2018SP | Trilha .Net - Obtendo metricas com TDD utilizando build automatiz...
TDC2018SP | Trilha .Net - Obtendo metricas com TDD utilizando build automatiz...TDC2018SP | Trilha .Net - Obtendo metricas com TDD utilizando build automatiz...
TDC2018SP | Trilha .Net - Obtendo metricas com TDD utilizando build automatiz...
 
TDC2018SP | Trilha .Net - .NET funcional com F#
TDC2018SP | Trilha .Net - .NET funcional com F#TDC2018SP | Trilha .Net - .NET funcional com F#
TDC2018SP | Trilha .Net - .NET funcional com F#
 
TDC2018SP | Trilha .Net - Crie SPAs com Razor e C# usando Blazor em .Net Core
TDC2018SP | Trilha .Net - Crie SPAs com Razor e C# usando Blazor  em .Net CoreTDC2018SP | Trilha .Net - Crie SPAs com Razor e C# usando Blazor  em .Net Core
TDC2018SP | Trilha .Net - Crie SPAs com Razor e C# usando Blazor em .Net Core
 

Último

SURVEY I created for uni project research
SURVEY I created for uni project researchSURVEY I created for uni project research
SURVEY I created for uni project research
CaitlinCummins3
 

Último (20)

Mattingly "AI and Prompt Design: LLMs with NER"
Mattingly "AI and Prompt Design: LLMs with NER"Mattingly "AI and Prompt Design: LLMs with NER"
Mattingly "AI and Prompt Design: LLMs with NER"
 
BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...
BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...
BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...
 
Basic Civil Engineering notes on Transportation Engineering, Modes of Transpo...
Basic Civil Engineering notes on Transportation Engineering, Modes of Transpo...Basic Civil Engineering notes on Transportation Engineering, Modes of Transpo...
Basic Civil Engineering notes on Transportation Engineering, Modes of Transpo...
 
PSYPACT- Practicing Over State Lines May 2024.pptx
PSYPACT- Practicing Over State Lines May 2024.pptxPSYPACT- Practicing Over State Lines May 2024.pptx
PSYPACT- Practicing Over State Lines May 2024.pptx
 
How to Manage Closest Location in Odoo 17 Inventory
How to Manage Closest Location in Odoo 17 InventoryHow to Manage Closest Location in Odoo 17 Inventory
How to Manage Closest Location in Odoo 17 Inventory
 
Exploring Gemini AI and Integration with MuleSoft | MuleSoft Mysore Meetup #45
Exploring Gemini AI and Integration with MuleSoft | MuleSoft Mysore Meetup #45Exploring Gemini AI and Integration with MuleSoft | MuleSoft Mysore Meetup #45
Exploring Gemini AI and Integration with MuleSoft | MuleSoft Mysore Meetup #45
 
male presentation...pdf.................
male presentation...pdf.................male presentation...pdf.................
male presentation...pdf.................
 
When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...
 
Mattingly "AI and Prompt Design: LLMs with Text Classification and Open Source"
Mattingly "AI and Prompt Design: LLMs with Text Classification and Open Source"Mattingly "AI and Prompt Design: LLMs with Text Classification and Open Source"
Mattingly "AI and Prompt Design: LLMs with Text Classification and Open Source"
 
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
 
Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...
 
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptxAnalyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
 
Championnat de France de Tennis de table/
Championnat de France de Tennis de table/Championnat de France de Tennis de table/
Championnat de France de Tennis de table/
 
How to Analyse Profit of a Sales Order in Odoo 17
How to Analyse Profit of a Sales Order in Odoo 17How to Analyse Profit of a Sales Order in Odoo 17
How to Analyse Profit of a Sales Order in Odoo 17
 
Major project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategiesMajor project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategies
 
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading RoomSternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
 
IPL Online Quiz by Pragya; Question Set.
IPL Online Quiz by Pragya; Question Set.IPL Online Quiz by Pragya; Question Set.
IPL Online Quiz by Pragya; Question Set.
 
SURVEY I created for uni project research
SURVEY I created for uni project researchSURVEY I created for uni project research
SURVEY I created for uni project research
 
ANTI PARKISON DRUGS.pptx
ANTI         PARKISON          DRUGS.pptxANTI         PARKISON          DRUGS.pptx
ANTI PARKISON DRUGS.pptx
 
“O BEIJO” EM ARTE .
“O BEIJO” EM ARTE                       .“O BEIJO” EM ARTE                       .
“O BEIJO” EM ARTE .
 

TDC2016SP - JooQ: SQL orientado a objetos.