Vous êtes sur la page 1sur 13

Spring Fundamental Training Part7

Let us turn our attention to spring database support. Spring supports a


wide variety of database strategies for accessing your database. I am
going to briefly introduce the JDBC.
JDBC is horrible. I would never want to use it in a real project directly.
Spring support for JDBC make JDBC usable, bearable and even
sometimes pleasurable. So I am going to create a DAO (Data Access
Object) and I will wire it up. Once it is wired, I will introduce the spring
JDBCTemplate class. This class gives so much support.
Very wisely spring team decided not to implement their own database
access technology. There are too many tried and tested techniques
already available.
JDBC: This library is probably one of the oldest Java libraries. It is
along established library, I guess more than 23 years old. Millions
of lines of production code out there in the real world depends
on it. It is a solid API but really a horrible API to work with. It is
very low level but it does at least work.
JPA: More recently in Java we have the JPA (Java Persistence
API). This is the industry standard technique for automating SQL
and removing the need to convert database rows into objects.
Hibernate: Several years ago a developer called Gavin King wrote
an open-source framework called Hibernate which took the java
world by storm. Today JPA is the official standard, but hibernate
API is still used by many projects around the world.
MyBatis: Another choice that you could use to simplify your
database access is called MyBatis. This framework is used to be
called IBatis.
There are lots more framework out there in the java world. These are
the most commonly used.
There are so many APIs out there to simplify data base access but
spring decided instead of competing with them they would simply
provide support built into spring so that whatever type of spring
application you are writing you can very easily integrate with your
database access technology of your choice.
In this session I will be focusing on how you can improve your JDBC
code using spring. Below is the architecture that you have worked on so
far in the provided sessions:

There is a client calling some server-side code which is put in the


class called BookService or rather we have implemented an
interface called BookService.
As we were not having knowledge to implement a proper Book
Service so we implemented MockBookService. It is basically a
good idea as it allows to hard code some stock data so that we
could test the client tier, we could test xml and all the rest of it. So
we know our system is hanging together.
Its time now to get rid of MockBookService and to switch it for the
more a sophisticated implementation. Now I am going to write a class
called BookServiceImpl.
This by the way is the good practice in Java project, when you see a
class with just a plain regular name followed by Impl, you are
suggesting that this is the production standard implementation.
BookServiceImpl is going to call a data access object, abbreviated as
D-A-O. DAO is a long standing pattern in java programming circles
and, not just java in fact but certainly Java programmers use the term
a lot. It is fairly simple idea, we abstract all of our database operations
into DAO class. So, if for example we are calling JDBC, then we have
all of our JDBC code encapsulated into that DAO. This means that if
we need to change database technology later, we can do so without
affecting any of the other tiers in our application.
It is all about good layering of the architecture. Below is the Interface I
have coded:

The above mentioned methods are what you typically see in DAOs,
create, read, update and delete.
Below is the project structure:

Inside the data package I have created BookDao.java interface.

Next obvious thing that I am going to do this with DAO is to come up


with some kind of implementation with it. Now to illustrate how helpful
spring can be I have coded below implementation.
In the above implementation I am using regular JDBC. This is a kind of
implementation you would have written without any framework like
spring.
If you will look at the constructor I am setting up the driver, this is
a routine line of code in JDBC that I have to type in just to force
the JVM the required driver class into memory.
I am then calling a private method called createTables. I have
added this method to purely make this sample code self-
contained. When this code will be run, it will try to create a table
to hold books. If this fails then the assumption is that the table
already exists.
I have implemented each of the method that appears in the
interface using straightforward JDBC. Whole block of code in the
create method is to insert single row in the database.

I have to access a connection, set the connection, and prepare a


statement the insert statement. I have to bind the parameters
into the SQL statements and then I have to execute the updates.
Then I have got to do resource management. I have got a finally
block where the operation is mandatory to happen. I have to be
careful to close everything that I have used. I have got to handle
any exceptions as well.
In the allBooks method the query is even worse than an update.
The point of all this is that I have implemented Dao using the most
basic API that we can use without any of springs help. Most important
thing about this code is that I am not 100% sure that it is completely
safe. Have I closed all kind of resources properly? Is there any edge
case if I get the exception in the wrong place?
Now in this session I am going to use the spring support to clean up
above code and to make it safer.

Spring framework supplies a class called JDBCTemplate and you can


think of this as a kind of helper class. It is going to help our DAO, it is
going to remove a lot of that repetitive code, in particular all of the
try-catch blocks.
In the above snapshot I have created an UML symbol that just means
that the BookDaoJdbcImpl is going to hold a reference to this
reference as an attribute. This object is going to be injected as
dependency through wiring. You can go with constructor injection.
Let us see what the template object is going to do for us. Consider the
create method. Now we can do the insert in a single line of code:

I have passed the sql statement that I want to be issued for the
database along with the values I wanted to save. You can use other
version of update as per your requirement.
What the template object do is that before it issue the SQL it will
automatically acquire a database connection, it will prepare the
statement and then it will execute the statement that I passed in
together with all of the values correctly bound into that SQL. Finally it
will clean up the resources it used. I might need to think about
exception handling but I will talk about it in another session.
NOTE: If some class is being used only in one class, then it is common
to declare the required class in the same file. I have created the one
called BookMapper. The rule in java that you can only have one public
class in the file but you have inner classes if required.
Below is the implementation:
Please refer spring doc to know the RowMapper working in detail.
I will be discussing in next session about wiring JDBCTemplate and
how to write a nice and clean DAO.

Vous aimerez peut-être aussi