SlideShare a Scribd company logo
1 of 22
Download to read offline
Get Back in Control of your SQL
SQL and Java could work
together so much better if
we only let them.

Copyright (c) 2009-2013 by Data Geekery GmbH. Slides licensed under CC BY SA 3.0
Intro

SQL and Java

About my motivation

SQL dominates database systems
SQL seems «low level» and «dusty»
SQL can do so much more
SQL should be «sexy» again

Copyright (c) 2009-2013 by Data Geekery GmbH. Slides licensed under CC BY SA 3.0

jOOQ

Examples
Intro

SQL and Java

jOOQ

JDBC

PreparedStatement stmt = connection.prepareStatement(
"SELECT text FROM products WHERE cust_id = ? AND value < ?");
stmt.setInt(1, custID);
stmt.setBigDecimal(2, BigDecimal.ZERO);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
System.out.println(rs.getString("TEXT"));
}

Copyright (c) 2009-2013 by Data Geekery GmbH. Slides licensed under CC BY SA 3.0

Examples
Intro

SQL and Java

JDBC – the naked truth

01:
02:
03:
04:
05:
06:
07:
08:
09:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:

PreparedStatement stmt = connection.prepareStatement(
"SELECT p.text txt" +
(isAccount ? ", NVL(a.type, ?) " : "") +
"FROM products p " +
(isAccount ? " INNER JOIN accounts a USING (prod_id) " : "") +
" WHERE p.cust_id = ? AND p.value < ?" +
(isAccount ? " AND a.type LIKE '%" + type + "%'" : "");
stmt.setInt(1, defaultType);
stmt.setInt(2, custID);
stmt.setBigDecimal(3, BigDecimal.ZERO);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
Clob clob = rs.getClob("TEXT");
System.out.println(clob.getSubString(1, (int) clob.length());
}
rs.close();
stmt.close();

Copyright (c) 2009-2013 by Data Geekery GmbH. Slides licensed under CC BY SA 3.0

jOOQ

Examples
Intro

SQL and Java

jOOQ

Examples

JDBC – the naked truth

01:
02:
03:
04:
05:
06:
07:
08:
09:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:

PreparedStatement stmt = connection.prepareStatement(
//
"SELECT p.text txt" +
//
(isAccount ? ", NVL(a.type, ?) " : "") +
//
"FROM products p " +
// Syntax error when isAccount == false
(isAccount ? " INNER JOIN accounts a USING (prod_id) " : "") + //
" WHERE p.cust_id = ? AND p.value < ?" +
//
(isAccount ? " AND a.type LIKE '%" + type + "%'" : "");
// Syntax error and SQL injection possible
stmt.setInt(1, defaultType);
// Wrong bind index
stmt.setInt(2, custID);
//
stmt.setBigDecimal(3, BigDecimal.ZERO);
//
ResultSet rs = stmt.executeQuery();
//
while (rs.next()) {
Clob clob = rs.getClob("TEXT");
System.out.println(clob.getSubString(1, (int) clob.length());
}

//
// ojdbc6: clob.free() should be called
//
//

rs.close();
stmt.close();

// close() not really in finally block
//

Copyright (c) 2009-2013 by Data Geekery GmbH. Slides licensed under CC BY SA 3.0
Intro

SQL and Java

EJB 2.0 EntityBeans

public interface CustomerRequest extends EJBObject {
BigInteger getId();
String getText();
void setText(String text);
@Override
void remove();
}
public interface CustomerRequestHome extends EJBHome {
CustomerRequest create(BigInteger id);
CustomerRequest find(BigInteger id);
}

Copyright (c) 2009-2013 by Data Geekery GmbH. Slides licensed under CC BY SA 3.0

jOOQ

Examples
Intro

SQL and Java

EJB 2.0 – the naked truth

<weblogic-enterprise-bean>
<ejb-name>com.example.CustomerRequestHome</ejb-name>
<entity-descriptor>
<pool>
<max-beans-in-free-pool>100</max-beans-in-free-pool>
</pool>
<entity-cache>
<max-beans-in-cache>500</max-beans-in-cache>
<idle-timeout-seconds>10</idle-timeout-seconds>
<concurrency-strategy>Database</concurrency-strategy>
</entity-cache>
<persistence>
<delay-updates-until-end-of-tx>True</delay-updates-until-end-of-tx>
</persistence>
<entity-clustering>
<home-is-clusterable>False</home-is-clusterable>
<home-load-algorithm>round-robin</home-load-algorithm>
</entity-clustering>
</entity-descriptor>
<transaction-descriptor/>
<enable-call-by-reference>True</enable-call-by-reference>
<jndi-name>com.example.CustomerRequestHome</jndi-name>
</weblogic-enterprise-bean>

Copyright (c) 2009-2013 by Data Geekery GmbH. Slides licensed under CC BY SA 3.0

jOOQ

Examples
Intro

SQL and Java

Hibernate – ORM

Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(new Event("Conference", new Date());
session.save(new Event("After Party", new Date());
List result = session.createQuery("from Event").list();
for (Event event : (List<Event>) result) {
System.out.println("Event : " + event.getTitle());
}
session.getTransaction().commit();
session.close();

Copyright (c) 2009-2013 by Data Geekery GmbH. Slides licensed under CC BY SA 3.0

jOOQ

Examples
Intro

SQL and Java

Hibernate – «navigation»

List result = session.createQuery("from Event").list();
for (Event event : (List<Event>) result) {
System.out.println("Participants of " + event);
for (Person person : event.getParticipants()) {
Company company = person.getCompany();
System.out.println(person + " (" + company + ")");

}
}

Copyright (c) 2009-2013 by Data Geekery GmbH. Slides licensed under CC BY SA 3.0

jOOQ

Examples
Intro

SQL and Java

jOOQ

Hibernate – the naked truth

<hibernate-mapping package="org.hibernate.tutorial.hbm">
<class name="Event" table="EVENTS">
<id name="id" column="EVENT_ID">
<generator class="increment"/>
</id>
<property name="date" type="timestamp" column="EVENT_DATE"/>
<property name="title"/>
<set name="participants" inverse="true">
<key column="eventId"/>
<one-to-many entity-name="Person"/>
</set>
</class>
</hibernate-mapping>

Copyright (c) 2009-2013 by Data Geekery GmbH. Slides licensed under CC BY SA 3.0

Examples
Intro

SQL and Java

jOOQ

JPA and EJB 3.0

EntityManager em = factory.createEntityManager();
em.getTransaction().begin();
em.persist(new Event("Conference", new Date());
em.persist(new Event("After Party", new Date());
List result = em.createQuery("from Event").getResultList();
for (Event event : (List<Event>) result) {
System.out.println("Event : " + event.getTitle());
}
em.getTransaction().commit();
em.close();

Copyright (c) 2009-2013 by Data Geekery GmbH. Slides licensed under CC BY SA 3.0

Examples
Intro

SQL and Java

jOOQ

EJB 3.0 – the naked truth

@Entity @Table(name = "EVENTS")
public class Event {
private Long id;
private String title;
private Date date;
@Id @GeneratedValue(generator = "increment")
@GenericGenerator(name = "increment", strategy = "increment")
public Long getId() { /* … */ }
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "EVENT_DATE")
public Date getDate() { /* … */ }

Copyright (c) 2009-2013 by Data Geekery GmbH. Slides licensed under CC BY SA 3.0

Examples
Intro

SQL and Java

jOOQ

Examples

EJB 3.0 – Annotatiomania™

@OneToMany(mappedBy = "destCustomerId")
@ManyToMany
@Fetch(FetchMode.SUBSELECT)
@JoinTable(
name = "customer_dealer_map",
joinColumns = {
@JoinColumn(name = "customer_id", referencedColumnName = "id")
},
inverseJoinColumns = {
@JoinColumn(name = "dealer_id", referencedColumnName = "id")
}
)
private Collection dealers;
Found at http://stackoverflow.com/q/17491912/521799
Copyright (c) 2009-2013 by Data Geekery GmbH. Slides licensed under CC BY SA 3.0
Intro

SQL and Java

jOOQ

Examples

JPA 3.0 Preview – Annotatiomania™

@OneToMany @OneToManyMore @AnyOne @AnyBody
@ManyToMany @Many
@Fetch @FetchMany @FetchWithDiscriminator(name = "no_name")
@JoinTable(joinColumns = {
@JoinColumn(name = "customer_id", referencedColumnName = "id")
})
@PrefetchJoinWithDiscriminator
@IfJoiningAvoidHashJoins @ButUseHashJoinsWhenMoreThan(records = 1000)
@XmlDataTransformable @SpringPrefechAdapter
private Collection employees;

Might not be true
Copyright (c) 2009-2013 by Data Geekery GmbH. Slides licensed under CC BY SA 3.0
Intro

SQL and Java

jOOQ

Examples

Criteria – the naked truth

EntityManager em= ...
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Person> criteria = builder.createQuery(Person.class);
Root<Person> person = criteria.from(Person.class);
Predicate condition = builder.gt(person.get(Person_.age), 20);
criteria.where(condition);
TypedQuery<Person> query = em.createQuery(query);
List<Person> result = query.getResultList();

Found at http://docs.oracle.com/javaee/6/tutorial/doc/gjrij.html
Copyright (c) 2009-2013 by Data Geekery GmbH. Slides licensed under CC BY SA 3.0
Intro

SQL and Java

NoSQL?

…

Copyright (c) 2009-2013 by Data Geekery GmbH. Slides licensed under CC BY SA 3.0

jOOQ

Examples
Intro

SQL and Java

jOOQ

NoSQL?

Seen at the O’Reilly Strata Conf:
History of NoSQL by Mark Madsen. Picture published by Edd Dumbill
Copyright (c) 2009-2013 by Data Geekery GmbH. Slides licensed under CC BY SA 3.0

Examples
Intro

SQL and Java

jOOQ

Examples

SQL is so much more

|
TEXT | VOTES |
RANK | PERCENT |
|-------------|-------|------------|---------|
|
Hibernate | 1383 |
1 |
32 % |
|
jOOQ | 1029 |
2 |
23 % |
| EclipseLink |
881 |
3 |
20 % |
|
JDBC |
533 |
4 |
12 % |
| Spring JDBC |
451 |
5 |
10 % |
Data may not be accurate…

Copyright (c) 2009-2013 by Data Geekery GmbH. Slides licensed under CC BY SA 3.0
Intro

SQL and Java

jOOQ

SQL is so much more

SELECT

p.text,
p.votes,
DENSE_RANK() OVER (ORDER BY p.votes DESC) AS "rank",
LPAD(
(p.votes * 100 / SUM(p.votes) OVER ()) || ' %',
4, ' '
) AS "percent"
FROM
poll_options p
WHERE
p.poll_id = 12
ORDER BY p.votes DESC

Copyright (c) 2009-2013 by Data Geekery GmbH. Slides licensed under CC BY SA 3.0

Examples
Intro

SQL and Java

jOOQ

The same with jOOQ

select (p.TEXT,
p.VOTES,
denseRank().over().orderBy(p.VOTES.desc()).as("rank"),
lpad(
p.VOTES.mul(100).div(sum(p.VOTES).over()).concat(" %"),
4, " "
).as("percent"))
.from
(POLL_OPTIONS.as("p"))
.where (p.POLL_ID.eq(12))
.orderBy(p.VOTES.desc());

Copyright (c) 2009-2013 by Data Geekery GmbH. Slides licensed under CC BY SA 3.0

Examples
Intro

SQL and Java

jOOQ

The same with jOOQ in Scala (!)

select (p.TEXT,
p.VOTES,
denseRank() over() orderBy(p.VOTES desc) as "rank",
lpad(
(p.VOTES * 100) / (sum(p.VOTES) over()) || " %",
4, " "
) as "percent")
from
(POLL_OPTIONS as "p")
where
(p.POLL_ID === 12)
orderBy (p.VOTES desc)

Copyright (c) 2009-2013 by Data Geekery GmbH. Slides licensed under CC BY SA 3.0

Examples
Intro

SQL and Java

Examples

Copyright (c) 2009-2013 by Data Geekery GmbH. Slides licensed under CC BY SA 3.0

jOOQ

Examples

More Related Content

What's hot

Get Back in Control of Your SQL - #33rdDegree
Get Back in Control of Your SQL - #33rdDegreeGet Back in Control of Your SQL - #33rdDegree
Get Back in Control of Your SQL - #33rdDegreeDataGeekery
 
10 Reasons Why we Love Some APIs and Why we Hate Some Others
10 Reasons Why we Love Some APIs and Why we Hate Some Others10 Reasons Why we Love Some APIs and Why we Hate Some Others
10 Reasons Why we Love Some APIs and Why we Hate Some OthersLukas Eder
 
2000 lines of java or 50 lines of sql the choice is yours - Lukas Eder
2000 lines of java or 50 lines of sql the choice is yours - Lukas Eder2000 lines of java or 50 lines of sql the choice is yours - Lukas Eder
2000 lines of java or 50 lines of sql the choice is yours - Lukas EderJAXLondon_Conference
 
Getting start Java EE Action-Based MVC with Thymeleaf
Getting start Java EE Action-Based MVC with ThymeleafGetting start Java EE Action-Based MVC with Thymeleaf
Getting start Java EE Action-Based MVC with ThymeleafMasatoshi Tada
 
JIOWA Code Generation Framework & Template Engine
JIOWA Code Generation Framework & Template EngineJIOWA Code Generation Framework & Template Engine
JIOWA Code Generation Framework & Template EngineRobert Mencl
 
Eddystone Beacons - Physical Web - Giving a URL to All Objects
Eddystone Beacons - Physical Web - Giving a URL to All ObjectsEddystone Beacons - Physical Web - Giving a URL to All Objects
Eddystone Beacons - Physical Web - Giving a URL to All ObjectsJeff Prestes
 
JSLounge - TypeScript 소개
JSLounge - TypeScript 소개JSLounge - TypeScript 소개
JSLounge - TypeScript 소개Reagan Hwang
 
Migrating from Struts 1 to Struts 2
Migrating from Struts 1 to Struts 2Migrating from Struts 1 to Struts 2
Migrating from Struts 1 to Struts 2Matt Raible
 
CiklumJavaSat_15112011:Alex Kruk VMForce
CiklumJavaSat_15112011:Alex Kruk VMForceCiklumJavaSat_15112011:Alex Kruk VMForce
CiklumJavaSat_15112011:Alex Kruk VMForceCiklum Ukraine
 
Questioning the status quo
Questioning the status quoQuestioning the status quo
Questioning the status quoIvano Pagano
 
There's more than web
There's more than webThere's more than web
There's more than webMatt Evans
 
Css2011 Ruo Ando
Css2011 Ruo AndoCss2011 Ruo Ando
Css2011 Ruo AndoRuo Ando
 
Industrializing the creation of machine images and Docker containers for clou...
Industrializing the creation of machine images and Docker containers for clou...Industrializing the creation of machine images and Docker containers for clou...
Industrializing the creation of machine images and Docker containers for clou...OW2
 
10 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 2020
10 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 202010 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 2020
10 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 2020Matt Raible
 
Spring Up Your Graph
Spring Up Your GraphSpring Up Your Graph
Spring Up Your GraphVMware Tanzu
 

What's hot (18)

Get Back in Control of Your SQL - #33rdDegree
Get Back in Control of Your SQL - #33rdDegreeGet Back in Control of Your SQL - #33rdDegree
Get Back in Control of Your SQL - #33rdDegree
 
Scala and Spring
Scala and SpringScala and Spring
Scala and Spring
 
10 Reasons Why we Love Some APIs and Why we Hate Some Others
10 Reasons Why we Love Some APIs and Why we Hate Some Others10 Reasons Why we Love Some APIs and Why we Hate Some Others
10 Reasons Why we Love Some APIs and Why we Hate Some Others
 
2000 lines of java or 50 lines of sql the choice is yours - Lukas Eder
2000 lines of java or 50 lines of sql the choice is yours - Lukas Eder2000 lines of java or 50 lines of sql the choice is yours - Lukas Eder
2000 lines of java or 50 lines of sql the choice is yours - Lukas Eder
 
Getting start Java EE Action-Based MVC with Thymeleaf
Getting start Java EE Action-Based MVC with ThymeleafGetting start Java EE Action-Based MVC with Thymeleaf
Getting start Java EE Action-Based MVC with Thymeleaf
 
JIOWA Code Generation Framework & Template Engine
JIOWA Code Generation Framework & Template EngineJIOWA Code Generation Framework & Template Engine
JIOWA Code Generation Framework & Template Engine
 
Eddystone Beacons - Physical Web - Giving a URL to All Objects
Eddystone Beacons - Physical Web - Giving a URL to All ObjectsEddystone Beacons - Physical Web - Giving a URL to All Objects
Eddystone Beacons - Physical Web - Giving a URL to All Objects
 
Physical web
Physical webPhysical web
Physical web
 
JSLounge - TypeScript 소개
JSLounge - TypeScript 소개JSLounge - TypeScript 소개
JSLounge - TypeScript 소개
 
Migrating from Struts 1 to Struts 2
Migrating from Struts 1 to Struts 2Migrating from Struts 1 to Struts 2
Migrating from Struts 1 to Struts 2
 
CiklumJavaSat_15112011:Alex Kruk VMForce
CiklumJavaSat_15112011:Alex Kruk VMForceCiklumJavaSat_15112011:Alex Kruk VMForce
CiklumJavaSat_15112011:Alex Kruk VMForce
 
Questioning the status quo
Questioning the status quoQuestioning the status quo
Questioning the status quo
 
There's more than web
There's more than webThere's more than web
There's more than web
 
Css2011 Ruo Ando
Css2011 Ruo AndoCss2011 Ruo Ando
Css2011 Ruo Ando
 
Industrializing the creation of machine images and Docker containers for clou...
Industrializing the creation of machine images and Docker containers for clou...Industrializing the creation of machine images and Docker containers for clou...
Industrializing the creation of machine images and Docker containers for clou...
 
10 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 2020
10 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 202010 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 2020
10 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 2020
 
Spring Up Your Graph
Spring Up Your GraphSpring Up Your Graph
Spring Up Your Graph
 
TDC 2016 - Arquitetura Java - Spring Cloud
TDC 2016 - Arquitetura Java - Spring CloudTDC 2016 - Arquitetura Java - Spring Cloud
TDC 2016 - Arquitetura Java - Spring Cloud
 

Similar to Get Back in Control of Your SQL with jOOQ at #Java2Days

Best Way to Write SQL in Java
Best Way to Write SQL in JavaBest Way to Write SQL in Java
Best Way to Write SQL in JavaGerger
 
Bkbiet day2 & 3
Bkbiet day2 & 3Bkbiet day2 & 3
Bkbiet day2 & 3mihirio
 
NoSQL? No, SQL! – How to Calculate Running Totals - Our Talk at the JUGS Bern
NoSQL? No, SQL! – How to Calculate Running Totals - Our Talk at the JUGS BernNoSQL? No, SQL! – How to Calculate Running Totals - Our Talk at the JUGS Bern
NoSQL? No, SQL! – How to Calculate Running Totals - Our Talk at the JUGS BernDataGeekery
 
10 SQL Tricks that You Didn't Think Were Possible
10 SQL Tricks that You Didn't Think Were Possible10 SQL Tricks that You Didn't Think Were Possible
10 SQL Tricks that You Didn't Think Were PossibleLukas Eder
 
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)Igor Bronovskyy
 
Struts 2 + Spring
Struts 2 + SpringStruts 2 + Spring
Struts 2 + SpringBryan Hsueh
 
Sqladria 2009 SRC
Sqladria 2009 SRCSqladria 2009 SRC
Sqladria 2009 SRCtepsum
 
Backbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCBackbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCpootsbook
 
JDBC for CSQL Database
JDBC for CSQL DatabaseJDBC for CSQL Database
JDBC for CSQL Databasejitendral
 
Defcon_Oracle_The_Making_of_the_2nd_sql_injection_worm
Defcon_Oracle_The_Making_of_the_2nd_sql_injection_wormDefcon_Oracle_The_Making_of_the_2nd_sql_injection_worm
Defcon_Oracle_The_Making_of_the_2nd_sql_injection_wormguest785f78
 
Going Offline with Gears And GWT
Going Offline with Gears And GWTGoing Offline with Gears And GWT
Going Offline with Gears And GWTtom.peck
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyDavid Padbury
 
Java one 2010
Java one 2010Java one 2010
Java one 2010scdn
 
닷넷 개발자를 위한 패턴이야기
닷넷 개발자를 위한 패턴이야기닷넷 개발자를 위한 패턴이야기
닷넷 개발자를 위한 패턴이야기YoungSu Son
 
TDC2016SP - Construindo Microserviços usando Spring Cloud
TDC2016SP - Construindo Microserviços usando Spring CloudTDC2016SP - Construindo Microserviços usando Spring Cloud
TDC2016SP - Construindo Microserviços usando Spring Cloudtdc-globalcode
 

Similar to Get Back in Control of Your SQL with jOOQ at #Java2Days (20)

Best Way to Write SQL in Java
Best Way to Write SQL in JavaBest Way to Write SQL in Java
Best Way to Write SQL in Java
 
Bkbiet day2 & 3
Bkbiet day2 & 3Bkbiet day2 & 3
Bkbiet day2 & 3
 
Lecture17
Lecture17Lecture17
Lecture17
 
Jdbc
JdbcJdbc
Jdbc
 
Jdbc ja
Jdbc jaJdbc ja
Jdbc ja
 
NoSQL? No, SQL! – How to Calculate Running Totals - Our Talk at the JUGS Bern
NoSQL? No, SQL! – How to Calculate Running Totals - Our Talk at the JUGS BernNoSQL? No, SQL! – How to Calculate Running Totals - Our Talk at the JUGS Bern
NoSQL? No, SQL! – How to Calculate Running Totals - Our Talk at the JUGS Bern
 
Advance java
Advance javaAdvance java
Advance java
 
10 SQL Tricks that You Didn't Think Were Possible
10 SQL Tricks that You Didn't Think Were Possible10 SQL Tricks that You Didn't Think Were Possible
10 SQL Tricks that You Didn't Think Were Possible
 
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
 
Struts 2 + Spring
Struts 2 + SpringStruts 2 + Spring
Struts 2 + Spring
 
Sqladria 2009 SRC
Sqladria 2009 SRCSqladria 2009 SRC
Sqladria 2009 SRC
 
Backbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCBackbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVC
 
Jdbc
JdbcJdbc
Jdbc
 
JDBC for CSQL Database
JDBC for CSQL DatabaseJDBC for CSQL Database
JDBC for CSQL Database
 
Defcon_Oracle_The_Making_of_the_2nd_sql_injection_worm
Defcon_Oracle_The_Making_of_the_2nd_sql_injection_wormDefcon_Oracle_The_Making_of_the_2nd_sql_injection_worm
Defcon_Oracle_The_Making_of_the_2nd_sql_injection_worm
 
Going Offline with Gears And GWT
Going Offline with Gears And GWTGoing Offline with Gears And GWT
Going Offline with Gears And GWT
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight Guy
 
Java one 2010
Java one 2010Java one 2010
Java one 2010
 
닷넷 개발자를 위한 패턴이야기
닷넷 개발자를 위한 패턴이야기닷넷 개발자를 위한 패턴이야기
닷넷 개발자를 위한 패턴이야기
 
TDC2016SP - Construindo Microserviços usando Spring Cloud
TDC2016SP - Construindo Microserviços usando Spring CloudTDC2016SP - Construindo Microserviços usando Spring Cloud
TDC2016SP - Construindo Microserviços usando Spring Cloud
 

Recently uploaded

Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
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 WorkerThousandEyes
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
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...Drew Madelung
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
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 2024The Digital Insurer
 

Recently uploaded (20)

Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
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
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 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...
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
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
 

Get Back in Control of Your SQL with jOOQ at #Java2Days

  • 1. Get Back in Control of your SQL SQL and Java could work together so much better if we only let them. Copyright (c) 2009-2013 by Data Geekery GmbH. Slides licensed under CC BY SA 3.0
  • 2. Intro SQL and Java About my motivation SQL dominates database systems SQL seems «low level» and «dusty» SQL can do so much more SQL should be «sexy» again Copyright (c) 2009-2013 by Data Geekery GmbH. Slides licensed under CC BY SA 3.0 jOOQ Examples
  • 3. Intro SQL and Java jOOQ JDBC PreparedStatement stmt = connection.prepareStatement( "SELECT text FROM products WHERE cust_id = ? AND value < ?"); stmt.setInt(1, custID); stmt.setBigDecimal(2, BigDecimal.ZERO); ResultSet rs = stmt.executeQuery(); while (rs.next()) { System.out.println(rs.getString("TEXT")); } Copyright (c) 2009-2013 by Data Geekery GmbH. Slides licensed under CC BY SA 3.0 Examples
  • 4. Intro SQL and Java JDBC – the naked truth 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: PreparedStatement stmt = connection.prepareStatement( "SELECT p.text txt" + (isAccount ? ", NVL(a.type, ?) " : "") + "FROM products p " + (isAccount ? " INNER JOIN accounts a USING (prod_id) " : "") + " WHERE p.cust_id = ? AND p.value < ?" + (isAccount ? " AND a.type LIKE '%" + type + "%'" : ""); stmt.setInt(1, defaultType); stmt.setInt(2, custID); stmt.setBigDecimal(3, BigDecimal.ZERO); ResultSet rs = stmt.executeQuery(); while (rs.next()) { Clob clob = rs.getClob("TEXT"); System.out.println(clob.getSubString(1, (int) clob.length()); } rs.close(); stmt.close(); Copyright (c) 2009-2013 by Data Geekery GmbH. Slides licensed under CC BY SA 3.0 jOOQ Examples
  • 5. Intro SQL and Java jOOQ Examples JDBC – the naked truth 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: PreparedStatement stmt = connection.prepareStatement( // "SELECT p.text txt" + // (isAccount ? ", NVL(a.type, ?) " : "") + // "FROM products p " + // Syntax error when isAccount == false (isAccount ? " INNER JOIN accounts a USING (prod_id) " : "") + // " WHERE p.cust_id = ? AND p.value < ?" + // (isAccount ? " AND a.type LIKE '%" + type + "%'" : ""); // Syntax error and SQL injection possible stmt.setInt(1, defaultType); // Wrong bind index stmt.setInt(2, custID); // stmt.setBigDecimal(3, BigDecimal.ZERO); // ResultSet rs = stmt.executeQuery(); // while (rs.next()) { Clob clob = rs.getClob("TEXT"); System.out.println(clob.getSubString(1, (int) clob.length()); } // // ojdbc6: clob.free() should be called // // rs.close(); stmt.close(); // close() not really in finally block // Copyright (c) 2009-2013 by Data Geekery GmbH. Slides licensed under CC BY SA 3.0
  • 6. Intro SQL and Java EJB 2.0 EntityBeans public interface CustomerRequest extends EJBObject { BigInteger getId(); String getText(); void setText(String text); @Override void remove(); } public interface CustomerRequestHome extends EJBHome { CustomerRequest create(BigInteger id); CustomerRequest find(BigInteger id); } Copyright (c) 2009-2013 by Data Geekery GmbH. Slides licensed under CC BY SA 3.0 jOOQ Examples
  • 7. Intro SQL and Java EJB 2.0 – the naked truth <weblogic-enterprise-bean> <ejb-name>com.example.CustomerRequestHome</ejb-name> <entity-descriptor> <pool> <max-beans-in-free-pool>100</max-beans-in-free-pool> </pool> <entity-cache> <max-beans-in-cache>500</max-beans-in-cache> <idle-timeout-seconds>10</idle-timeout-seconds> <concurrency-strategy>Database</concurrency-strategy> </entity-cache> <persistence> <delay-updates-until-end-of-tx>True</delay-updates-until-end-of-tx> </persistence> <entity-clustering> <home-is-clusterable>False</home-is-clusterable> <home-load-algorithm>round-robin</home-load-algorithm> </entity-clustering> </entity-descriptor> <transaction-descriptor/> <enable-call-by-reference>True</enable-call-by-reference> <jndi-name>com.example.CustomerRequestHome</jndi-name> </weblogic-enterprise-bean> Copyright (c) 2009-2013 by Data Geekery GmbH. Slides licensed under CC BY SA 3.0 jOOQ Examples
  • 8. Intro SQL and Java Hibernate – ORM Session session = sessionFactory.openSession(); session.beginTransaction(); session.save(new Event("Conference", new Date()); session.save(new Event("After Party", new Date()); List result = session.createQuery("from Event").list(); for (Event event : (List<Event>) result) { System.out.println("Event : " + event.getTitle()); } session.getTransaction().commit(); session.close(); Copyright (c) 2009-2013 by Data Geekery GmbH. Slides licensed under CC BY SA 3.0 jOOQ Examples
  • 9. Intro SQL and Java Hibernate – «navigation» List result = session.createQuery("from Event").list(); for (Event event : (List<Event>) result) { System.out.println("Participants of " + event); for (Person person : event.getParticipants()) { Company company = person.getCompany(); System.out.println(person + " (" + company + ")"); } } Copyright (c) 2009-2013 by Data Geekery GmbH. Slides licensed under CC BY SA 3.0 jOOQ Examples
  • 10. Intro SQL and Java jOOQ Hibernate – the naked truth <hibernate-mapping package="org.hibernate.tutorial.hbm"> <class name="Event" table="EVENTS"> <id name="id" column="EVENT_ID"> <generator class="increment"/> </id> <property name="date" type="timestamp" column="EVENT_DATE"/> <property name="title"/> <set name="participants" inverse="true"> <key column="eventId"/> <one-to-many entity-name="Person"/> </set> </class> </hibernate-mapping> Copyright (c) 2009-2013 by Data Geekery GmbH. Slides licensed under CC BY SA 3.0 Examples
  • 11. Intro SQL and Java jOOQ JPA and EJB 3.0 EntityManager em = factory.createEntityManager(); em.getTransaction().begin(); em.persist(new Event("Conference", new Date()); em.persist(new Event("After Party", new Date()); List result = em.createQuery("from Event").getResultList(); for (Event event : (List<Event>) result) { System.out.println("Event : " + event.getTitle()); } em.getTransaction().commit(); em.close(); Copyright (c) 2009-2013 by Data Geekery GmbH. Slides licensed under CC BY SA 3.0 Examples
  • 12. Intro SQL and Java jOOQ EJB 3.0 – the naked truth @Entity @Table(name = "EVENTS") public class Event { private Long id; private String title; private Date date; @Id @GeneratedValue(generator = "increment") @GenericGenerator(name = "increment", strategy = "increment") public Long getId() { /* … */ } @Temporal(TemporalType.TIMESTAMP) @Column(name = "EVENT_DATE") public Date getDate() { /* … */ } Copyright (c) 2009-2013 by Data Geekery GmbH. Slides licensed under CC BY SA 3.0 Examples
  • 13. Intro SQL and Java jOOQ Examples EJB 3.0 – Annotatiomania™ @OneToMany(mappedBy = "destCustomerId") @ManyToMany @Fetch(FetchMode.SUBSELECT) @JoinTable( name = "customer_dealer_map", joinColumns = { @JoinColumn(name = "customer_id", referencedColumnName = "id") }, inverseJoinColumns = { @JoinColumn(name = "dealer_id", referencedColumnName = "id") } ) private Collection dealers; Found at http://stackoverflow.com/q/17491912/521799 Copyright (c) 2009-2013 by Data Geekery GmbH. Slides licensed under CC BY SA 3.0
  • 14. Intro SQL and Java jOOQ Examples JPA 3.0 Preview – Annotatiomania™ @OneToMany @OneToManyMore @AnyOne @AnyBody @ManyToMany @Many @Fetch @FetchMany @FetchWithDiscriminator(name = "no_name") @JoinTable(joinColumns = { @JoinColumn(name = "customer_id", referencedColumnName = "id") }) @PrefetchJoinWithDiscriminator @IfJoiningAvoidHashJoins @ButUseHashJoinsWhenMoreThan(records = 1000) @XmlDataTransformable @SpringPrefechAdapter private Collection employees; Might not be true Copyright (c) 2009-2013 by Data Geekery GmbH. Slides licensed under CC BY SA 3.0
  • 15. Intro SQL and Java jOOQ Examples Criteria – the naked truth EntityManager em= ... CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery<Person> criteria = builder.createQuery(Person.class); Root<Person> person = criteria.from(Person.class); Predicate condition = builder.gt(person.get(Person_.age), 20); criteria.where(condition); TypedQuery<Person> query = em.createQuery(query); List<Person> result = query.getResultList(); Found at http://docs.oracle.com/javaee/6/tutorial/doc/gjrij.html Copyright (c) 2009-2013 by Data Geekery GmbH. Slides licensed under CC BY SA 3.0
  • 16. Intro SQL and Java NoSQL? … Copyright (c) 2009-2013 by Data Geekery GmbH. Slides licensed under CC BY SA 3.0 jOOQ Examples
  • 17. Intro SQL and Java jOOQ NoSQL? Seen at the O’Reilly Strata Conf: History of NoSQL by Mark Madsen. Picture published by Edd Dumbill Copyright (c) 2009-2013 by Data Geekery GmbH. Slides licensed under CC BY SA 3.0 Examples
  • 18. Intro SQL and Java jOOQ Examples SQL is so much more | TEXT | VOTES | RANK | PERCENT | |-------------|-------|------------|---------| | Hibernate | 1383 | 1 | 32 % | | jOOQ | 1029 | 2 | 23 % | | EclipseLink | 881 | 3 | 20 % | | JDBC | 533 | 4 | 12 % | | Spring JDBC | 451 | 5 | 10 % | Data may not be accurate… Copyright (c) 2009-2013 by Data Geekery GmbH. Slides licensed under CC BY SA 3.0
  • 19. Intro SQL and Java jOOQ SQL is so much more SELECT p.text, p.votes, DENSE_RANK() OVER (ORDER BY p.votes DESC) AS "rank", LPAD( (p.votes * 100 / SUM(p.votes) OVER ()) || ' %', 4, ' ' ) AS "percent" FROM poll_options p WHERE p.poll_id = 12 ORDER BY p.votes DESC Copyright (c) 2009-2013 by Data Geekery GmbH. Slides licensed under CC BY SA 3.0 Examples
  • 20. Intro SQL and Java jOOQ The same with jOOQ select (p.TEXT, p.VOTES, denseRank().over().orderBy(p.VOTES.desc()).as("rank"), lpad( p.VOTES.mul(100).div(sum(p.VOTES).over()).concat(" %"), 4, " " ).as("percent")) .from (POLL_OPTIONS.as("p")) .where (p.POLL_ID.eq(12)) .orderBy(p.VOTES.desc()); Copyright (c) 2009-2013 by Data Geekery GmbH. Slides licensed under CC BY SA 3.0 Examples
  • 21. Intro SQL and Java jOOQ The same with jOOQ in Scala (!) select (p.TEXT, p.VOTES, denseRank() over() orderBy(p.VOTES desc) as "rank", lpad( (p.VOTES * 100) / (sum(p.VOTES) over()) || " %", 4, " " ) as "percent") from (POLL_OPTIONS as "p") where (p.POLL_ID === 12) orderBy (p.VOTES desc) Copyright (c) 2009-2013 by Data Geekery GmbH. Slides licensed under CC BY SA 3.0 Examples
  • 22. Intro SQL and Java Examples Copyright (c) 2009-2013 by Data Geekery GmbH. Slides licensed under CC BY SA 3.0 jOOQ Examples