Tutorial for Spring DAO with JDBC



Similar documents
Evaluation. Copy. Evaluation Copy. Chapter 7: Using JDBC with Spring. 1) A Simpler Approach ) The JdbcTemplate. Class...

Spring Data JDBC Extensions Reference Documentation

The junit Unit Tes(ng Tool for Java

CS2506 Operating Systems II Lab 8, 8 th Tue/03 /2011 Java API

Supplement IV.C: Tutorial for Oracle. For Introduction to Java Programming By Y. Daniel Liang

Supplement IV.D: Tutorial for MS Access. For Introduction to Java Programming By Y. Daniel Liang

Licensed for viewing only. Printing is prohibited. For hard copies, please purchase from

Unit Testing and JUnit

Install BA Server with Your Own BA Repository

Using Netbeans and the Derby Database for Projects Contents

OTN Developer Day Enterprise Java. Hands on Lab Manual JPA 2.0 and Object Relational Mapping Basics

Overview of Web Services API

public void setusername(string username) { this.username = username; } public void setname(string name) { this.name = name; }

Using the DataDirect Connect for JDBC Drivers with the Sun Java System Application Server

Effective unit testing with JUnit

NGASI AppServer Manager SaaS/ASP Hosting Automation for Cloud Computing Administrator and User Guide

Table of Contents. LESSON: The JUnit Test Tool...1. Subjects...2. Testing What JUnit Provides...4. JUnit Concepts...5

Aspect Oriented Programming. with. Spring

Clustering a Grails Application for Scalability and Availability

Database Migration Plugin - Reference Documentation

Java and Databases. COMP514 Distributed Information Systems. Java Database Connectivity. Standards and utilities. Java and Databases

Oracle Forms Services Secure Web.Show_Document() calls to Oracle Reports Server 6i

Implementing a Web Service Client using Java

HOW TO DEPLOY AN EJB APLICATION IN WEBLOGIC SERVER 11GR1

Web Service Caching Using Command Cache

Java and RDBMS. Married with issues. Database constraints

Module Title: : Cloud Application Development

PDQ-Wizard Prototype 1.0 Installation Guide

Author: Sascha Wolski Sebastian Hennebrueder Tutorials for Struts, EJB, xdoclet and eclipse.

SpagoBI exo Tomcat Installation Manual

Using Actian PSQL as a Data Store with VMware vfabric SQLFire. Actian PSQL White Paper May 2013

Application note: Connecting the to a Database

BEAWebLogic. Portal. WebLogic Portlets for SAP Installation Guide

JDBC. It is connected by the Native Module of dependent form of h/w like.dll or.so. ex) OCI driver for local connection to Oracle

IBM DB2 XML support. How to Configure the IBM DB2 Support in oxygen

TABLE OF CONTENTS...2 INTRODUCTION...3 APPLETS AND APPLICATIONS...3 JAVABEANS...4 EXCEPTION HANDLING...5 JAVA DATABASE CONNECTIVITY (JDBC)...

Brekeke SIP Server Version 3 Using a Third-Party Database Tutorial Brekeke Software, Inc.

Tutorial for Creating Resources in Java - Client

How To Write An Online Shopping Application In Java Ee

Third-Party Software Support. Converting from SAS Table Server to a SQL Server Database

OPENRULES. Database Integration. Open Source Business Decision Management System. Release 6.2.1

Database Access from a Programming Language: Database Access from a Programming Language

Database Access from a Programming Language:

LAB 6: Code Generation with Visual Paradigm for UML and JDBC Integration

Hibernate Language Binding Guide For The Connection Cloud Using Java Persistence API (JAP)

Hadoop Integration Guide

Core Java+ J2EE+Struts+Hibernate+Spring

Java EE Web Development Course Program

Mobile Solutions for Data Collection. Sarah Croft and Laura Pierik

SPRING INTERVIEW QUESTIONS

Kony MobileFabric. Sync Windows Installation Manual - WebSphere. On-Premises. Release 6.5. Document Relevance and Accuracy

Unit-testing with JML

Querying Databases Using the DB Query and JDBC Query Nodes

Talend for Data Integration guide

Package sjdbc. R topics documented: February 20, 2015

Implementing the Shop with EJB

OpenReports: Users Guide

jcolibri2 Tutorial Juan A. Recio-García Belén Díaz-Agudo Pedro González-Calero September 16, 2008 Document version 1.2

Creating A Walking Skeleton

JDBC (Java / SQL Programming) CS 377: Database Systems

Chapter 1: Web Services Testing and soapui

Running and Testing Java EE Applications in Embedded Mode with JupEEter Framework

Chapter 9 Java and SQL. Wang Yang wyang@njnet.edu.cn

Comparing the Effectiveness of Penetration Testing and Static Code Analysis

JUnit Automated Software Testing Framework. Jeff Offutt. SWE 437 George Mason University Thanks in part to Aynur Abdurazik. What is JUnit?

Unit Testing. and. JUnit

Using SQL Server Management Studio

IBM InfoSphere MDM Server v9.0. Version: Demo. Page <<1/11>>

Services. Relational. Databases & JDBC. Today. Relational. Databases SQL JDBC. Next Time. Services. Relational. Databases & JDBC. Today.

Plugin JUnit. Contents. Mikaël Marche. November 18, 2005

Slides prepared by : Farzana Rahman TESTING WITH JUNIT IN ECLIPSE

Tutorial: How to Use SQL Server Management Studio from Home

EDI Process Specification

This document summarizes the steps of deploying ActiveVOS on oracle Weblogic Platform.

Developing an EJB3 Application. on WebSphere 6.1. using RAD 7.5

Getting Started with the Internet Communications Engine

Exam Name: IBM InfoSphere MDM Server v9.0

Module 4: File Reading. Module 5: Database connection

PASS4TEST 専 門 IT 認 証 試 験 問 題 集 提 供 者

Active Directory Authentication Integration

Livezilla How to Install on Shared Hosting By: Jon Manning

Customer Bank Account Management System Technical Specification Document

Test Automation Integration with Test Management QAComplete

ArpViewer Manual Version Datum

Kuali Security Request Installation Guide

SharePoint AD Information Sync Installation Instruction

Installation Guide. Version 2.1. on Oracle Java Cloud Service

Installing the ASP.NET VETtrak APIs onto IIS 5 or 6

Java Programming. JDBC Spring Framework Web Services

System i Windows Integration Solutions

How To Test A Load Test On A Java Testnet 2.5 (For A Testnet) On A Test Server On A Microsoft Web Server On An Ipad Or Ipad (For An Ipa) On Your Computer Or Ipa

CONFIGURATION AND APPLICATIONS DEPLOYMENT IN WEBSPHERE 6.1

OLH: Oracle Loader for Hadoop OSCH: Oracle SQL Connector for Hadoop Distributed File System (HDFS)

Witango Application Server 6. Installation Guide for OS X

Implementing SQI via SOAP Web-Services

Transcription:

Overview Tutorial for Spring DAO with JDBC Prepared by: Nigusse Duguma This tutorial demonstrates how to work with data access objects in the spring framework. It implements the Spring Data Access Object with JDBC. Data Access Objects exist to provide a means to read, write or modify data in the database. In this tutorial basic ways of bean definition and good features of spring like Dependency Injection (setter injector in this case) and ways of declaring beans in the Spring configuration file are demonstrated. In addition a Junit test is used to test the code. Eclipse 3.1 is used as implementation environment. And MySQL is used for the database. Table of Contents: Steps. Creating the Database Schema and a table. Setting up the environment Creating the Project in Eclipse Creating folders for organizing the Java source codes configuring logging Creating the Beans Interfaces and Implementations Creating Configuration file Testing the Application 1. Create a database schema named DEMO, on your database server. 2. Using following SQL Script to create the USER Table under the database DEMO. CREATE TABLE DEMO.USER ( UID INTEGER UNSIGNED NOT NULL AUTO_INCREMENT, USERNAME VARCHAR(45) NOT NULL, PASSWORD VARCHAR(45) NOT NULL, PRIMARY KEY (`UID`) ); Page 1

3. Start Eclipse and create a new Project. You may create a new Java project. Name the project as springjdbcdemo. 4. Under this project create a folder called Jsrc where all your Java Source Codes will be stored. 5. Under Jsrc create a folder called User To organize our objects let's create the following packages under Jsrc > user user > DAO The DAO Interface class will be stored here > DAO > Impl The implementation of the DAO interface will be stored here. > DAO > Test The JUnit test code will be stored here. user > Domain All the domain objects will be stored here. Eg. User.java. The project structure will look like as in the following picture. Page 2

Configuring logging Spring depends on Log4j. Make sure that the Log4j JAR file is in the applications classpath. If it is not already provided with the spring libraries you can find it at http://logging.apache.org/log4j/docs/index.html. Download the file log4j and copy it to the lib folder under your project. Creating the Beans Spring allows to use the so-called Plain Java Objects for the domain classes or of the business logic. The class User is a normal Java bean with private attributes and public getter/setters and constructor method. 6. Create the domain object user.domain.user.java, This is a plain old Java object to represent the table USER. A partial implementation is as follows: you complete the getters and setters package user.domain; public class User { private Integer uid; private String username; private String password; public User(Integer uid, String username, String password) { this.setuid(uid); this.setusername(username); this.password(password); // Add Getters and Setters here Interface class and its Implementation 7. Next create an Interface class UserDao.java under, user.dao which tell the contract that the UserDaoImpl.java implements. package user. Dao; import user.domain.user; public interface UserDao { int insertuser(user record); int updateuser(user record); void deleteuser(int key); User selectuser(int key); Page 3

Configuration with Spring config files 7. Let's now create the configuration file called appcontext..xml under config directory. The following init method initializes the applicationcontext which gives us the Spring core container from the configuration files. public synchronized void init() { if (appcontext == null) { try { String path = System.getProperty("user.dir"); String slash = System.getProperty("file.separator"); String configdir = path + slash + "config" + slash; appcontext = new FileSystemXmlApplicationContext( new String[] {configdir + "appcontext.xml"); catch(exception e) { System.err.println(e.getMessage()); 8. The Spring XML configuration file is the base for the Spring Core Container. The <bean> elements are the most basic configuration unit in spring. <?xml version="1.0" encoding="utf-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd"> </beans> <!-- Define your beans here --> 9. First let's define the DataSource bean. This tells spring the url, user name, password and driver of the database. We can also add other parameters for pooling too. We need to add the commons-dbcp-1.2.2.jar Page 4

and commons-pool-1.3.jar files in to our library. These are freely available on www.apache.org web site. Download and add them to the folder lib. <bean id="datasource" class="org.apache.commons.dbcp.basicdatasource" destroy-method="close"> <property name="driverclassname" value="com.mysql.jdbc.driver"/> <property name="url" value="jdbc: mysql://localhost:3306/test"/> <property name="username" value="username"/> <property name="password" value="password"/> <property name="maxactive" value="10"/> <property name="maxidle" value="5"/> <property name="minidle" value="1"/> <property name="poolpreparedstatements" value="true"/> <property name="initialsize" value="1"/> </bean> 10.We next define the transactionmanager bean which helps to create the JDBC transaction manager for the DataSource. <bean id="transactionmanager" class="org.springframework.jdbc.datasource.datasourcetransactionmanager"> <property name="datasource" ref="datasource"/> </bean> 11.Next let's implement UserDao.java interface using UserDaoImpl.java class. This class needs DataSourceTransactionManager to access the database. Declare a private variable DataSourceTransactionManager. definition for the UserDao object will be as follows: The bean <bean id="userdao" class="user.dao.impl.userdaoimpl"> <property name="transactionmanager" ref="transactionmanager"/> </bean> For simplicity let's get our data source object from the transaction manager, which will help us to create spring JdbcTemplate object. We can use the JdbcTemplate instance variable to execute SQL Scripts. We initialize the JdbcTemplate on the constructor. Page 5

The full implementation of the UserDaoImpl.java is given as follows. Here Spring's setter injection method is used. (Note the comments for detail implementation of each method.) package user.dao.impl; import java.sql.resultset; import java.sql.sqlexception; import java.sql.types; import javax.sql.datasource; import org.springframework.jdbc.core.jdbctemplate; import org.springframework.jdbc.core.rowcallbackhandler; import org.springframework.jdbc.datasource.datasourcetransactionmanager; import user.dao.userdao; import user.domain.user; public class UserDaoImpl implements UserDao { private DataSourceTransactionManager transactionmanager; private JdbcTemplate jdbctemplate; public UserDaoImpl() { super(); DataSource datasource = transactionmanager.getdatasource(); jdbctemplate = new JdbcTemplate(dataSource); // Spring setter injector used public void settransactionmanager(datasourcetransactionmanager transactionmanager) {this.transactionmanager = transactionmanager; public int insertuser(user record) { // SQL to insert User Id, User Name & Password String sql = "Insert Into DEMO.USER (UID, USERNAME, PASSWORD) values (?,?,?)"; // Set parameters and JDBC types Object[] params = new Object[] {record.getuid(), record.getusername(), record.getpassword(); int[] types = new int[] {Types.INTEGER, Types.VARCHAR, Types.VARCHAR; return jdbctemplate.update(sql, params, types); public User selectuser(int key) { String sql = "select UID, USERNAME, PASSWORD from DEMO.USER where UID =?"; final Object[] params = new Object[] {key; Page 6

// Creating object being queried final User user = new User(); // Process query results jdbctemplate.query(sql, params, new RowCallbackHandler() { public void processrow (ResultSet rs) throws SQLException { user.setuid(new Integer(rs.getInt("UID"))); user.setusername(rs.getstring("username")); user.setpassword(rs.getstring("password")); ); return user; // returns queried object public void deleteuser(int key) { String sql = "delete from DEMO.USER where UID =? "; Object[] params = new Object[] {key; jdbctemplate.update(sql, params); public int updateuser(user record) { String sql = "update DEMO.USER (USERNAME, PASSWORD) set (?,?) where UID =?"; // passing parameters and types Object[] params = new Object[] {record.getusername(), record.getpassword(), record.getuid(); int[] types = new int[] {Types.VARCHAR, Types.VARCHAR, Types.INTEGER; return jdbctemplate.update(sql, params, types); Testing Using Junit Test Junit is a testing framework. Creating tests in Junit is simply a matter of extending the junit.framework.testcase class and implementing one or more test method. Therefor we use a JUNIT Test to test the methods implemented above work as intended and to see the results of data insertion. For more details about Junit test you can visit www.junit.org. The UserDAOTest class tests weather the classes are implemented with out error and show the result of writing data to the table User Page 7

package User.dao.test; import junit.framework.test; import junit.framework.testcase; import junit.framework.testsuite; import org.apache.log4j.xml.domconfigurator; import org.springframework.context.applicationcontext; import org.springframework.context.support.filesystemxmlapplicationcontext; import User.dao.UserDao; import User.domain.User; public class UserDaoTest extends TestCase{ private static final Integer UID = new Integer(1); private static final String USRID = "username"; private static final String PSWD = "password"; protected static ApplicationContext appcontext; private UserDao userdao; public UserDaoTest(String arg) { super(arg); public static Test suite() { TestSuite suite = new TestSuite(); suite.addtest(new UserDaoTest("testUserDAO")); return suite; public void setup() throws Exception { init(); userdao = (UserDao) getbean("userdao"); public static void main(string[] args) { junit.textui.testrunner.run(suite()); public synchronized void init() { if (appcontext == null) { try { String path = System.getProperty("user.dir"); String slash = System.getProperty("file.separator"); String configdir = path + slash + "config" + slash; DOMConfigurator.configure(configDir + "log4j.xml"); appcontext = new FileSystemXmlApplicationContext( Page 8

new String[] {configdir + "appcontext.xml"); catch(exception e) { System.err.println(e.getMessage()); protected Object getbean(string beanname) { return appcontext.getbean(beanname); public void testuserdao() { User record = new User(); record.setuid(uid); record.setusername(usrid); record.setpassword(pswd); UserDao.insertUser(record); System.out.println("User is Inserted [" + UID + ", " + USRID + ", " + PSWD + "]"); User user = UserDao.selectUser(UID); assertequals(usrid, user.getusername()); System.out.println("User Selected [" + user.getuid() + ", " + user.getusername() + ", " + user.getpassword() + "]"); record.setusername("anotheruser"); int rowsaffected = UserDao.updateUser(record); assertequals(1, rowsaffected); user = UserDao.selectUser(UID); assertnotsame(usrid, user.getusername()); System.out.println("User is Updated [" + user.getuid() + ", " + user.getusername() + ", " + user.getpassword() + "]"); userdao.deleteuser(uid); user = userdao.selectuser(uid); assertequals(null, user.getusername()); System.out.println("User is Deleted [" + user.getuid() + ", " + user.getusername() + ", " + user.getpassword() + "]"); When run within a Junit runner this test can prove weather the data are inserted or not. If it runs successfully you will see the following result displayed. User is Inserted [1, username, password] User Selected [1, username, password] User is Updated [1, ANOTHERUSER, password] User is Deleted [null, null, null] Page 9

The screen snap shot of UserDaoTest shows the test is successful and the data are inserted. End of the Tutorial! Page 10