Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Kenneth A. Kousen - Making Java Groovy - 2014.pdf
Скачиваний:
50
Добавлен:
19.03.2016
Размер:
15.36 Mб
Скачать

Database access

This chapter covers

JDBC and the Groovy Sql class

Simplifying Hibernate and JPA using GORM

Working with the NoSQL database

Virtually every significant application uses persistent data in one form or another. The vast majority of them save the data in relational databases. To make it easy to switch from one database to another, Java provides the JDBC1 API. While JDBC does handle the required tasks, its low-level nature leads to many lines of code to handle even the simplest tasks.

Because the software is object-oriented and the database is relational, there’s a mismatch at the boundary. The open source Hibernate project attempts to bridge that gap at a higher level of abstraction. Java includes the Java Persistence API (JPA) as a uniform interface to Hibernate and other object-relational mapping (ORM) tools.

1You would think that JDBC stands for Java Database Connectivity. Everyone would agree with you, except for the people at Sun (now Oracle) who created the API. They claim that JDBC is a trademarked acronym that doesn’t stand for anything. Clearly lawyers were involved somewhere in the process. I’m not going to be bound by such silliness, and if I get sued as a result, I’ll be sure to blog about it.

199

www.it-ebooks.info

200

Java

JDBC

Java +

NoSQL

database

Groovy

APIs

 

Groovy

groovy.sql.Sql

CHAPTER 8 Database access

Hibernate

and JPA

 

 

Figure 8.1 Java uses JDBC and JPA,

 

 

 

 

with Hibernate being the most common

GORM

JPA provider. Most NoSQL databases

have a Java API that can be wrapped by

 

 

 

 

Groovy; in this chapter GMongo is used

 

 

to access MongoDB. GORM is a Groovy

 

 

DSL on top of Spring and Hibernate.

 

 

Finally, the groovy.sql.Sql class

 

 

makes it easy to use raw SQL with a

 

 

relational database.

Groovy, as usual, provides some simplifications to the Java APIs. For raw SQL, the Groovy standard library includes the groovy.sql.Sql class. For ORM tools like Hibernate, the Grails project created a domain-specific language (DSL) called GORM. Finally, many of the so-called “No SQL” databases that have become popular recently also provide Groovy APIs to simplify their use. Figure 8.1 shows the technologies covered in this chapter.

With relational databases everything ultimately comes down to SQL, so I’ll start there.

8.1The Java approach, part 1: JDBC

JDBC is a set of classes and interfaces that provide a thin layer over raw SQL. That’s a significant engineering achievement, actually. Providing a unified API across virtually every relational database is no trivial task, especially when each vendor implements significantly different variations in SQL itself. Still, if you already have the SQL worked out, the JDBC API has classes and methods to pass it to the database and process the results.

The following listing shows a simple example, based on a single persistent class called Product.

Listing 8.1 The Product class, a POJO mapped to a database table

package mjg;

public class Product { private int id; private String name; private double price;

public Product() {}

public Product(int id, String name, double price) { this.id = id;

this.name = name; this.price = price;

}

www.it-ebooks.info

The Java approach, part 1: JDBC

201

public int getId() { return id; }

public void setId(int id) { this.id = id; } public String getName() { return name; }

public void setName(String name) { this.name = name; } public double getPrice() { return price; }

public void setPrice(double price) { this.price = price; }

}

The Product class has only three attributes, one of which (id) will represent the primary key in the database. The rest of the class is simply constructors, getters and setters, and (not shown) the normal toString, equals, and hashCode overrides. The complete version is available in the book source code.

The next listing shows the ProductDAO interface.

Listing 8.2 A DAO interface for the Product class

import java.util.List;

public interface ProductDAO { List<Product> getAllProducts(); Product findProductById(int id); void insertProduct(Product p); void deleteProduct(int id);

}

To implement the interface I need to know the table structure. Again, to keep things simple, assume I only have a single table, called product. For the purposes of this example the table will be created in the DAO implementation class, using the H2 database.

The implementation class is JDBCProductDAO. A couple of excerpts are shown ahead. Java developers will find both the code and the attendant painful verbosity quite familiar.

The following listing shows the beginnings of the implementation, including constants to represent the URL and driver class.

Listing 8.3 A JDBC implementation of the DAO interface

public class JDBCProductDAO implements ProductDAO {

private static final String URL = "jdbc:h2:build/test"; private static final String DRIVER = "org.h2.Driver";

public JDBCProductDAO() { try {

Class.forName(DRIVER);

} catch (ClassNotFoundException e) { e.printStackTrace();

return;

}

createAndPopulateTable();

}

// ... More to come ...

}

www.it-ebooks.info

Everything in JDBC throws an SQLException
Only way to guarantee everything is closed
Yes, even close() throws an exception
Declared outside try/catch, to access in finally

202

CHAPTER 8 Database access

The import statements have been mercifully omitted. The private method to create and populate the table is shown in the next listing.

Listing 8.4 Adding creation and population of the Product table to the DAO

private void createAndPopulateTable() { Connection conn = null;

Statement stmt = null; try {

conn = DriverManager.getConnection(URL); stmt = conn.createStatement();

stmt.execute("drop table product if exists;"); stmt.execute("create table product (id int primary key, name " + "varchar(25), price double);");

stmt.executeUpdate("insert into product values " + "(1,'baseball',4.99),(2,'football',14.95),(3,'basketball',14.99)");

} catch (SQLException e) { e.printStackTrace();

} finally { try {

if (stmt != null) stmt.close(); if (conn != null) conn.close();

} catch (SQLException e) { e.printStackTrace();

}

}

A phrase often used when describing Java is that the essence is buried in ceremony. JDBC code is probably the worst offender in the whole API. The “essence” here is to create the table and add a few rows. The “ceremony” is all the boilerplate surrounding it. As the listing shows, try/catch blocks are needed because virtually everything in JDBC throws a checked SQLException. In addition, because it’s absolutely necessary to close the database connection whether an exception is thrown or not, the connection must be closed in a finally block. To make matters even uglier, the close method itself also throws an SQLException, so it, too, must be wrapped in a try/catch block, and of course the only way to avoid a potential NullPointerException is to verify that the connection and statement references are not null when they’re closed.

This boilerplate is repeated in every method in the DAO. For example, the following listing shows the implementation of the findProductById method.

Listing 8.5 The findProductById method with all the required ceremony

public Product findProductById(int id) { Product p = null;

Connection conn = null; PreparedStatement pst = null; try {

conn = DriverManager.getConnection(URL); pst = conn.prepareStatement(

"select * from product where id = ?"); pst.setInt(1, id);

The essence; everything else is ceremony

www.it-ebooks.info

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]