27
Copyright (c) 2009 - 2013 by Data Geekery GmbH. Get Back in Control of your SQL SQL and Java could work together so much better if we only let them .

jOOQ at Topconf 2013

Embed Size (px)

DESCRIPTION

The slides from Lukas Eder's jOOQ presentation at Topconf 2013. The slides talk about the history of the Java and SQL integration, starting with JDBC, EJB 2.0, Hibernate, JPA, culminating in the claim that SQL is evolving in an entirely different direction than what is covered by Enterprise Java. This is where jOOQ comes in. jOOQ is currently the only platform in the Java market aiming at making SQL a first-class citizen in Java. This website depicts what every CTO / software architect should consider at the beginning of every new Java project: http://www.hibernate-alternative.com This version of the presentation on Slideshare is licensed under the terms of the CC-BY-SA license 3.0: http://creativecommons.org/licenses/by-sa/3.0 The jOOQ name, the jOOQ logo and the picture with the harbour worker are trademarks by Data Geekery GmbH. Please contact us if you want to use our trademarks in a derived presentation of yours. [email protected]

Citation preview

Page 1: jOOQ at Topconf 2013

Copyright (c) 2009-2013 by Data Geekery GmbH.

Get Back in Control of your SQL

SQL and Java could worktogether so much better ifwe only let them.

Page 2: jOOQ at Topconf 2013

Copyright (c) 2009-2013 by Data Geekery GmbH.

Intro SQL and Java jOOQ Examples

About me

Java, SQL, PL/SQL

2001-2006 MSc Computer Science EPFL

2006-2009 Ergon Informatik AG, Zürich

2009-2013 Crealogix E-Banking AG, Zürich

2013 Adobe Systems Inc, Basel

2013 Data Geekery GmbH, Zürich

Page 3: jOOQ at Topconf 2013

Copyright (c) 2009-2013 by Data Geekery GmbH.

Intro SQL and Java jOOQ Examples

About my motivation

SQL dominates database systems

SQL seems «low level» and «dusty»

SQL can do so much more

SQL should be «sexy» again

Page 4: jOOQ at Topconf 2013

Copyright (c) 2009-2013 by Data Geekery GmbH.

Intro SQL and Java jOOQ Examples

About today

History of SQL in Java

Persistence in Java today

jOOQ

jOOQ Examples

Page 5: jOOQ at Topconf 2013

Copyright (c) 2009-2013 by Data Geekery GmbH.

Intro SQL and Java jOOQ Examples

SQL and Java - never ending story

JDBC

EJB 2.0 with EntityBeans

Hibernate / TopLink

EJB 3.0 with JPA 2.x

iBATIS / JDO / SpringData / 1’000 others

Page 6: jOOQ at Topconf 2013

Copyright (c) 2009-2013 by Data Geekery GmbH.

Intro SQL and Java jOOQ Examples

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"));

}

Page 7: jOOQ at Topconf 2013

Copyright (c) 2009-2013 by Data Geekery GmbH.

Intro SQL and Java jOOQ Examples

JDBC – the naked truth

01: PreparedStatement stmt = connection.prepareStatement(02: "SELECT p.text txt" + 03: (isAccount ? ", NVL(a.type, ?) " : "") + 04: "FROM products p " + 05: (isAccount ? " INNER JOIN accounts a USING (prod_id) " : "") + 06: " WHERE p.cust_id = ? AND p.value < ?" + 07: (isAccount ? " AND a.type LIKE '%" + type + "%'" : "");08: stmt.setInt(1, defaultType);09: stmt.setInt(2, custID);10: stmt.setBigDecimal(3, BigDecimal.ZERO);11: ResultSet rs = stmt.executeQuery();12:13: while (rs.next()) {14: Clob clob = rs.getClob("TEXT");15: System.out.println(clob.getSubString(1, (int) clob.length());16: } 17:18: rs.close();19: stmt.close();

Page 8: jOOQ at Topconf 2013

Copyright (c) 2009-2013 by Data Geekery GmbH.

Intro SQL and Java jOOQ Examples

JDBC – the naked truth

01: PreparedStatement stmt = connection.prepareStatement( //02: "SELECT p.text txt" + //03: (isAccount ? ", NVL(a.type, ?) " : "") + //04: "FROM products p " + // Syntax error when isAccount == false05: (isAccount ? " INNER JOIN accounts a USING (prod_id) " : "") + //06: " WHERE p.cust_id = ? AND p.value < ?" + //07: (isAccount ? " AND a.type LIKE '%" + type + "%'" : ""); // Syntax error and SQL injection possible08: stmt.setInt(1, defaultType); // Wrong bind index09: stmt.setInt(2, custID); //10: stmt.setBigDecimal(3, BigDecimal.ZERO); //11: ResultSet rs = stmt.executeQuery(); //12:13: while (rs.next()) { //14: Clob clob = rs.getClob("TEXT"); // ojdbc6: clob.free() should be called15: System.out.println(clob.getSubString(1, (int) clob.length()); // 16: } //17:18: rs.close(); // close() not really in finally block19: stmt.close(); //

Page 9: jOOQ at Topconf 2013

Copyright (c) 2009-2013 by Data Geekery GmbH.

Intro SQL and Java jOOQ Examples

JDBC – pros and cons

JDBC ProsNo restrictions (procedures, UDTs, vendor-specific features)

Simple

Fast

JDBC ConsString-based

No syntax checking

Lots of code, flat / indexed variablesRepetitive

Vendor lock-in

Page 10: jOOQ at Topconf 2013

Copyright (c) 2009-2013 by Data Geekery GmbH.

Intro SQL and Java jOOQ Examples

EJB 2.0 EntityBeans

public interface CustomerRequest extends EJBObject {BigInteger getId();String getText();void setText(String text);@Overridevoid remove();

}

public interface CustomerRequestHome extends EJBHome {CustomerRequest create(BigInteger id);CustomerRequest find(BigInteger id);

}

Page 11: jOOQ at Topconf 2013

Copyright (c) 2009-2013 by Data Geekery GmbH.

Intro SQL and Java jOOQ Examples

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>

Page 12: jOOQ at Topconf 2013

Copyright (c) 2009-2013 by Data Geekery GmbH.

Intro SQL and Java jOOQ Examples

EJB 2.0 – pros and cons

EJB 2.0 ProsIntuitive client code (create(), remove(), store())

Powerful (transactions, caching, etc.)

EJB 2.0 ConsNot intuitive implementation (Home, conventions)

Lots of configuration

XDoclet

Checked Exceptions (FinderException, CreateException)

Repetitive (except with a code generator)

Domain Model depends on container

Page 13: jOOQ at Topconf 2013

Copyright (c) 2009-2013 by Data Geekery GmbH.

Intro SQL and Java jOOQ Examples

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();

Page 14: jOOQ at Topconf 2013

Copyright (c) 2009-2013 by Data Geekery GmbH.

Intro SQL and Java jOOQ Examples

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 + ")");}

}

Page 15: jOOQ at Topconf 2013

Copyright (c) 2009-2013 by Data Geekery GmbH.

Intro SQL and Java jOOQ Examples

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>

Page 16: jOOQ at Topconf 2013

Copyright (c) 2009-2013 by Data Geekery GmbH.

Intro SQL and Java jOOQ Examples

Hibernate – pros and cons

Hibernate ProsVery intuitive client code (POJOs)

POJO code generator

Objects can be «navigated»

Hibernate implements JPA

Hibernate ConsHard to configure

Caching is complex

HQL is limited. SQL can do more.

ORM impedance mismatch

Page 17: jOOQ at Topconf 2013

Copyright (c) 2009-2013 by Data Geekery GmbH.

Intro SQL and Java jOOQ Examples

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();

Page 18: jOOQ at Topconf 2013

Copyright (c) 2009-2013 by Data Geekery GmbH.

Intro SQL and Java jOOQ Examples

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() { /* … */ }

Page 19: jOOQ at Topconf 2013

Copyright (c) 2009-2013 by Data Geekery GmbH.

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();

Page 20: jOOQ at Topconf 2013

Copyright (c) 2009-2013 by Data Geekery GmbH.

Intro SQL and Java jOOQ Examples

JPA – pros and cons

JPA FactsHibernate HQL => JPQL

Hibernate XML mapping => annotations

Hibernate Sessions => EntityManager

JPA ProsNext standard after EJB 2.0

Good implementations, such as Hibernate, EclipseLink

JPA ConsCriteriaQuery

Page 21: jOOQ at Topconf 2013

Copyright (c) 2009-2013 by Data Geekery GmbH.

Intro SQL and Java jOOQ Examples

What else is there?

iBATIS / MyBatisXML based. SQL is externalised

Active, but seems to be at the end of its hype cycle

JDOHas JDOQL (similar to HQL, JPQL)

Supports also NoSQL stores

Is pretty dead

Spring JDBC, Apache DbUtils, etcEase *some* of the JDBC pain

Page 22: jOOQ at Topconf 2013

Copyright (c) 2009-2013 by Data Geekery GmbH.

Intro SQL and Java jOOQ Examples

SQL is so much more

| TEXT | VOTES | RANK | PERCENT ||-------------|-------|------------|---------|| Hibernate | 138 | 1 | 32 % || jOOQ | 102 | 2 | 23 % || EclipseLink | 88 | 3 | 20 % || JDBC | 53 | 4 | 12 % || Spring JDBC | 45 | 5 | 10 % |

Page 23: jOOQ at Topconf 2013

Copyright (c) 2009-2013 by Data Geekery GmbH.

Intro SQL and Java jOOQ Examples

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 pWHERE p.poll_id = 12ORDER BY p.votes DESC

Page 24: jOOQ at Topconf 2013

Copyright (c) 2009-2013 by Data Geekery GmbH.

Intro SQL and Java jOOQ Examples

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());

Page 25: jOOQ at Topconf 2013

Copyright (c) 2009-2013 by Data Geekery GmbH.

Intro SQL and Java jOOQ Examples

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)

Page 26: jOOQ at Topconf 2013

Copyright (c) 2009-2013 by Data Geekery GmbH.

Intro SQL and Java jOOQ Examples

Support

Access MariaDB

CUBRID MySQL

DB2 Oracle

Derby Postgres

Firebird SQL Server

H2 SQLite

HSQLDB Sybase ASE

Ingres Sybase SQL Anywhere

Page 27: jOOQ at Topconf 2013

Copyright (c) 2009-2013 by Data Geekery GmbH.

Intro SQL and Java jOOQ Examples

Examples