What is JDBC?
The Java Database Connectivity (JDBC) API is the industry standard for database-independent connectivity between the Java programming language and a wide range of databases – SQL databases and other tabular data sources, such as spreadsheets or flat files. The JDBC API provides a call-level API for SQL-based database access.
Source: http://www.oracle.com/technetwork/java/javase/tech/index-jsp-136101.htmlWhat is HyperSQL?
HSQLDB (HyperSQL DataBase) is the leading SQL relational database engine written in Java. It has a JDBC driver and supports nearly full ANSI-92 SQL (BNF format) plus many SQL:2008 enhancements. It offers a small, fast multithreaded and transactional database engine which offers in-memory and disk-based tables and supports embedded and server modes. Additionally, it includes tools such as a command line SQL tool and GUI query tools.
Source: http://hsqldb.org/
Here's the folder structure of our application:
Let's begin by defining our Person object.
This is a simple POJO with four fields:
id firstName lastName moneySince we will manipulate a list of persons, let's declare a service that manipulates a list of Persons.
PersonService
We've declared a simple CRUD system with the following methods:
getAll add delete editIn each method we prepared a sql String (for example):
String sql = "delete from person where id = ?";If you have worked with a relational database before, that statement should be familiar already to you.
We also assigned parameters in each statement if required (for example):
MapHere we're using Named Parameters so that we easily interchange the order of the parameters.parameters = new HashMap (); parameters.put("firstName", firstName); parameters.put("lastName", lastName); parameters.put("money", money);
Notice in each method the actual database action is delegated to an instance of SimpleJdbcTemplate
What is a SimpleJdbcTemplate?
The SimpleJdbcTemplate class wraps the classic JdbcTemplate and leverages Java 5 language features such as varargs and autoboxing.What is a JdbcTemplate?
Source: http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/jdbc.html
The JdbcTemplate class is the central class in the JDBC core package. It handles the creation and release of resources, which helps you avoid common errors such as forgetting to close the connection. It performs the basic tasks of the core JDBC workflow such as statement creation and execution, leaving application code to provide SQL and extract results. The JdbcTemplate class executes SQL queries, update statements and stored procedure calls, performs iteration over ResultSets and extraction of returned parameter values. It also catches JDBC exceptions and translates them to the generic, more informative, exception hierarchy defined in the org.springframework.dao package.We're done with the Person object and the Service layer. Let's move to the Spring controller.
Source: http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/jdbc.html
MainController
This controller declares four mappings:
/persons /persons/add?firstname=''&lastname=''&money='' /persons/delete?id='' /persons/edit?id=''&firstname=''&lastname=''&money=''Each mapping delegates the call to the PersonService. When the PersonService is done processing, the controller then forwards the request to a JSP page that displays a confirmation message.
Added Page
addedpage.jsp
Edited Page
editedpage.jsp
Deleted Page
deletedpage.jsp
Main Page
To finish our Spring MVC application, we need to declare a couple of required XML configurations.
To enable Spring MVC we need to add it in the web.xml
web.xml
Take note of the URL pattern. When accessing any pages in our MVC application, the host name must be appended with
/krams
In the web.xml we declared a servlet-name spring. By convention, we must declare a spring-servlet.xml as well.
spring-servlet.xml
By convention, we must declare an applicationContext.xml as well.
applicationContext.xml
If you're following my previous tutorials, at this point, our application should now be finished. But we're not done yet. Notice in the applicationContext.xml, we declared the following import:
jdbc-context.xml
We basically encapsulated all JDBC and Spring related configurations in this one XML file. Here's what happening within the config:
1. Enable transaction support through Spring annotations:
2. Declare a datasource:
Our datasource uses C3P0 for pooling to allow efficient access to our database. Why do we need to wrap our datasource with a connection pool?
JDBC connections are often managed via a connection pool rather than obtained directly from the driver. Examples of connection pools include BoneCP, C3P0 and DBCP.
Source: http://en.wikipedia.org/wiki/Java_Database_Connectivity
What is Pooling?
In software engineering, a connection pool is a cache of database connections maintained so that the connections can be reused when future requests to the database are required. Connection pools are used to enhance the performance of executing commands on a database. Opening and maintaining a database connection for each user, especially requests made to a dynamic database-driven website application, is costly and wastes resources. In connection pooling, after a connection is created, it is placed in the pool and it is used over again so that a new connection does not have to be established.
Source: http://en.wikipedia.org/wiki/Connection_pool
There are different providers of pooling. C3P0 is one of the good ones.
For more info on configuring C3P0, you can check this reference from JBoss: HowTo configure the C3P0 connection pool. For a list of other pooling providers, see Open Source Database Connection Pools
The database-specific configuration are contained within a properties file.
spring.properties
As an alternative, we can enter these properties directly within the jdbc-context.xml
This is exactly similar to the following:
The benefit of using a separate properties file is we encapsulate all database-specific configs within a separate file. The jdbc-context.xml purpose is to encapsulate JDBC-related config not database properties.
Our application is now finished. We've managed to setup a simple Spring 3 MVC application with JDBC support. We've managed to build a CRUD system using JDBC. We've also leveraged Spring's MVC programming model via annotation.
To access the main page, enter the following URL:
http://localhost:8080/spring-jdbc/krams/main/persons
To add a new user, enter the following URL:
http://localhost:8080/spring-jdbc/krams/main/persons/add?firstname=John&lastname=Smith&money=1000
To delete a user, enter the following URL:
http://localhost:8080/spring-jdbc/krams/main/persons/delete?id=1
To edit a user, enter the following URL:
http://localhost:8080/spring-jdbc/krams/main//persons/edit?id=1&firstname=Johnny&lastname=Smith&money=2000
Just change the URL parameters to match the id that you're editing. If the id doesn't exist or the format is incorrect, expect an error to be thrown.
In order to make the application run, you need to run an instance of HSQLDB. If you're using Eclipse, all you need to do is import the whole project. Then find the hsqldb-2.0.0.jar on under the Libraries then do the following:
1. Right-click on the hsqldb-2.0.0.jar.
2. Select Run As.
3. Choose Server - org.hsqldb.server. This will run an instance of HSQLDB.
If you need a GUI, you can run the built-in Swing interface:
Here's how it looks like:
If you need further help, consult the HSQLDB documentation. If you want to use a different database, like MySQL, make sure to include the Java drivers first. Then update the spring.properties and hibernate.cfg.xml accordingly.
Because we're using JDBC here, we need to create the database schema manually. I have included the database sql_script within the project itself. You can import the schema from HSQLDB's Swing interface. The actual sql_script is really short:
The best way to learn further is to try the actual application.
Download the project
You can access the project site at Google's Project Hosting at http://code.google.com/p/spring-mvc-hibernate-annotations-integration-tutorial/
You can download the project as a Maven build. Look for the spring.jdbc.zip in the Download sections.
You can run the project directly using an embedded server via Maven.
For Tomcat: mvn tomcat:run
For Jetty: mvn jetty:run
If you want to learn more about Spring MVC and integration with other technologies, feel free to read my other tutorials in the Tutorials section.
Share the joy:
|
Subscribe by reader Subscribe by email Share