Chapter 18. Database Access

Introduction

Java can be used to access many kinds of databases. A database can be something as simple as a text file or a fast key/value pairing on disk (DBM format), as sophisticated as a SQL-based relational database management system (DBMS), as scalable as a cloud-based “NoSQL” database, or as exotic as an object database. That said, this chapter focuses on relational databases.

Regardless of how your data is actually stored, in many applications you’ll want to write a class called an accessor[53] to mediate between the database and the rest of the application. For example, if you are using JDBC, the answers to your query come back packaged in an object called a ResultSet, but it would not make sense to structure the rest of your application around the ResultSet because it’s JDBC-specific. In a Personal Information Manager application, the primary classes might be Person, Address, and Meeting. You would probably write a PersonAccessor class to request the names and addresses from the database and generate Person and Address objects from them. The DataAccessor objects would also take updates from the main program and store them into the database.

If this reminds you of Enterprise JavaBeans, you’re right. If you’re familiar with EJB 2 Entity Beans or JPA Entities (incorrectly but frequently called “EJ3 Entities”), you can think of simple entity beans as a specialized kind of data accessor. In fact, JPA provides a high-level mechanism for easily building ...

Get Java Cookbook, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.