In this page, we will demonstrate the use of criteria in retrieving records from database. Before we talk about criteria, let’s study the traditional way of retrieving database record through JDBC.
Select * from
JDBC, short for Java Database Connectivity, offers a set of Java API for Java program (programmer) to access relational database. With JDBC, programmers execute SQL statements to retrieve database record. Here is an example:
The JDBC way of accessing database works pretty well against simple Java applications. However, it possesses the following disadvantages/weaknesses, and they become more obvious and irritating when the size of application/database is large:
- It throws an uninformative SQL Exception for all kinds of problems that may happen when executing query.
- You must be familiar with SQL in order to construct the most efficient query to retrieve data, or else the performance may be low.
- With JDBC, it is the programmer’s responsibility to convert data gets from resultset to appropriate data type. The application may risk having runtime error if programmer failed to spot the wrong conversion of data type for an object get from result set. If the programmer can spot it during programming, he has to add more code for type checking, to surround the calls with try-catch, or check the data specification. All the solutions take time and are not 100 bug-free.
Criteria provides programmers with an elegant, object-oriented way in retrieving database records. Programmers can build queries using a criteria object, and list out properly typed records base on the requirements specified. The following piece of code shows the ‘criteria-way’ of getting a customer.
Criteria possesses the following advantages:
- Short learning curve. As long as the programmer has basic knowledge in Java programming, he/she should find no difficulties in constructing query with criteria. Best of all, no SQL knowledge is needed.
- Programmer can easily change a criterion without creating a new criteria object. The JDBC approach requires rewriting the whole SQL for little differences.
- The neat way of coding facilitates easy debugging.
Now, forget the bad experiences of debugging an essay-long SQL selection statement which failed to execute due to a typo, or due to the absent of a comma.