Use spring JdbcTemplate for curd operation

Source: Internet
Author: User
Tags stub

The

Project introduces a helper class (JDBC Template) for JDBC in spring that encapsulates the operation of JDBC and uses it to build a project project structure to create a MAVEN project, as shown in the figure above


Maven dependency jar Rollup

  <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit<
    /artifactid> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactid>javax.servlet-api</ artifactid> <version>3.1.0</version> </dependency> <dependency> &LT;GROUPID&GT;ORG.SPR Ingframework</groupid> <artifactId>spring-jdbc</artifactId> <version>4.2.4.release</ version> </dependency> <dependency> <groupId>mysql</groupId> <artifactid>my sql-connector-java</artifactid> <version>5.1.35</version> </dependency> <dependency > <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> < Version>4.2.4.release</version> </depenDency> </dependencies> 

New test class, creating data table
Package com.curd.spring.test;

Import Org.junit.Test;
Import org.springframework.jdbc.core.JdbcTemplate;
Import Org.springframework.jdbc.datasource.DriverManagerDataSource;

public class JdbcTemplate {
	@Test public
	Void Demo () {
		Drivermanagerdatasource datasource=new Drivermanagerdatasource ();
		Datasource.setdriverclassname ("Com.mysql.jdbc.Driver");
		Datasource.seturl ("Jdbc:mysql:///test");
		Datasource.setusername ("root");
		Datasource.setpassword ("");
		JdbcTemplate jdbctemplate=new JdbcTemplate (dataSource);
		Jdbctemplate.execute ("CREATE TABLE temp (' id ' int") not NULL, ' name ' varchar (+) DEFAULT NULL, ' password ' varchar (32) DEFAULT null,primary KEY (' id '));}
}

The table structure is created as follows Appliactioncontext.xml configuration file
<?xml version= "1.0" encoding= "UTF-8"?> <beans xmlns= "Http://www.springframework.org/schema/beans" xmlns: p= "http://www.springframework.org/schema/p" xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" Xsi:sche malocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans.xsd "> <!--Data Source configuration--<bean id=" DataSource "class=" Org.springframework.jdbc.datasource.DriverManagerDataSource "> <property name=" driverclassname "value=" Com.mysql.jdbc.Driver "></property> <property name=" url "value=" Jdbc:mysql:///test "></property > <property name= "username" value= "root" ></property> <property name= "password" value= "" ></ property> </bean> <bean id= "JdbcTemplate" class= "Org.springframework.jdbc.core.JdbcTemplate" > < Property Name= "DataSource" ref= "DataSource" ></property> </bean> <bean id= "Userdao" class= "com.cUrd.spring.dao.impl.UserDAOImpl "> <property name=" jdbctemplate "ref=" JdbcTemplate "></property> < /bean> </beans>

Note Modify the database configuration for your local configuration
Model class User.java
Package Com.curd.spring.model;

public class User {
	private int id;
	Private String username;
	private String password;
	public int getId () {
		return ID;
	}
	public void setId (int id) {
		this.id = ID;
	}
	Public String GetUserName () {
		return username;
	}
	public void Setusername (String username) {
		this.username = username;
	}
	Public String GetPassword () {
		return password;
	}
	public void SetPassword (String password) {
		this.password = password;
	}
	@Override public
	String toString () {
		return "User [id=" + ID + ", username=" + Username + ", password="
				+ P Assword + "]";
	}
	
	
}

Userdao Interface Iuserdao.java
Package Com.curd.spring.dao;

Import java.util.List;

Import Com.curd.spring.model.User;

Public interface Iuserdao {public
	void AddUser (user user);
    public void deleteuser (int id);
    public void UpdateUser (user user);
    Public String searchusername (int id);
    Public User searchuser (int id);
    Public list<user> findAll ();
}

Interface implementation Class Userdaoimpl.java in accordance with the previous spring dependency injection, we need to use the constructor in the interface implementation class to get JdbcTemplate, Spring has already helped us to think of this, it provides us with Jdbcdaosupport support class , all DAO inherits this class and will automatically get JdbcTemplate (provided that the injected DataSource) takes the action object directly from the getjdbctemplate in our implementation class.
JdbcTemplate mainly provides the following methods:
1. Execute method: Can be used to execute any SQL statements, generally used to execute DDL statements;
2, Update method and BatchUpdate method: Update method is used to execute new, modify, delete and other statements; The BatchUpdate method is used to execute batch-related statements;
3, Query method and Queryforxxx method: Used to execute query related statements;
4. Call method: Used to execute stored procedures, function-related statements. Package Com.curd.spring.dao.impl;
Import Java.sql.ResultSet;
Import java.sql.SQLException;

Import java.util.List;
Import Org.springframework.jdbc.core.RowMapper;

Import Org.springframework.jdbc.core.support.JdbcDaoSupport;
Import Com.curd.spring.dao.IUserDAO;

Import Com.curd.spring.model.User; public class Userdaoimpl extends Jdbcdaosupport implements Iuserdao {@Override public void AddUser (User user) {//T
		ODO auto-generated method stub String sql = "INSERT into temp values (?,?,?)";
	This.getjdbctemplate (). Update (SQL, Null,user.getusername (), User.getpassword ()); } @Override public void deleteuser (int id) {//TODO auto-generated method stub String sql = ' Delete from temp wher
		E id =? ";
	This.getjdbctemplate (). Update (SQL, ID); } @Override public void UpdateUser (user user) {//TODO auto-generated method stub String sql = "Update temp set us Ername =?,password=?
		WHERE id =? ";
	This.getjdbctemplate (). Update (SQL, User.getusername (), User.getpassword (), User.getid ()); } @Override Public String searchusername (int id) {//TODO auto-generated method stub String sql = "Select username from temp where id =?"
		;
	Return This.getjdbctemplate (). queryForObject (SQL, string.class, id); } @Override public User searchuser (int id) {//TODO auto-generated method stub String sql= ' select * FROM temp wher
		E id=? ";
	Return This.getjdbctemplate (). queryForObject (SQL, New Userrowmapper (), id); } @Override Public list<user> findAll () {//TODO auto-generated method stub String sql = ' SELECT * FROM Temp
		";
	Return this.getjdbctemplate (). query (SQL, New Userrowmapper ()); } class Userrowmapper implements Rowmapper<user> {//rs is the return result set, encapsulating the @Override public User maprow in each behavior unit (result
			Set rs, int rowNum) throws SQLException {//TODO auto-generated method Stub User user = new user ();
			User.setid (Rs.getint ("id"));
			User.setusername (rs.getstring ("username"));
			User.setpassword (rs.getstring ("password"));
		return user;
 }
	 }
}

Test class Usertest.java
Package com.curd.spring.test;



Import java.util.List;
Import Org.junit.Test;
Import Org.springframework.context.ApplicationContext;

Import Org.springframework.context.support.ClassPathXmlApplicationContext;
Import Com.curd.spring.dao.IUserDAO;


Import Com.curd.spring.model.User;
		public class Usertest {@Test public void Testadduser () {User user = new User ();
		User.setusername ("Liu");
		User.setpassword ("6");
		ApplicationContext CTX = new Classpathxmlapplicationcontext ("Applicationcontext.xml");
		Iuserdao DAO = (Iuserdao) ctx.getbean ("Userdao");
	Dao.adduser (user); } @Test public void Testdeleteuser () {ApplicationContext ctx = new Classpathxmlapplicationcontext ("Applicationcont
		Ext.xml ");
		Iuserdao DAO = (Iuserdao) ctx.getbean ("Userdao");
    Dao.deleteuser (1);
    
    };
    	@Test public void Testupdateuser () {User user = new User ();
    	User.setid (1);
    	User.setusername ("Zhi");
    	User.setpassword ("1234"); ApplicationContext CTX = new CLASSPAthxmlapplicationcontext ("Applicationcontext.xml");
    	Iuserdao DAO = (Iuserdao) ctx.getbean ("Userdao");
    Dao.updateuser (user);
    }; @Test public void Testsearchusername () {ApplicationContext ctx = new Classpathxmlapplicationcontext ("Applicationc
    	Ontext.xml ");
    	Iuserdao DAO = (Iuserdao) ctx.getbean ("Userdao");
    	String username = dao.searchusername (2);
    SYSTEM.OUT.PRINTLN (username);
    }; @Test public void Testsearchuser () {ApplicationContext ctx = new Classpathxmlapplicationcontext ("Applicationconte
    	Xt.xml ");
    	Iuserdao DAO = (Iuserdao) ctx.getbean ("Userdao");
    	
    	User u = dao.searchuser (2);
    	
    System.out.println (U.tostring ());
    }; @Test public void Testfindall () {ApplicationContext ctx = new Classpathxmlapplicationcontext ("ApplicationContext.
    	XML ");
    	Iuserdao DAO = (Iuserdao) ctx.getbean ("Userdao"); 	
    	list<user> u = dao.findall (); for (User user:u) {System.out.println (User.tostriNg ());
}
    	
    };
 }

Let's test it quickly. Summary of Knowledge points
1. Spring provides a support class for each persistence technology, injecting the template tool class into the DAO
(1) JDBC:org.springframework.jdbc.core.support.JdbcDaoSupport
(2) Hibernate 3.0:org.springframework.orm.hibernate3.support.hibernatedaosupport
(3) IBatis:org.springframework.orm.ibatis.support.SqlMapClientDaoSupport
The user writes DAO only needs to inherit Jdbcdaosupport, can inject JdbcTemplate
2. Add, modify, delete with int update (String sql, Object ... args) via JdbcTemplate
3, simple query, return the original data type, String type
String sql = "SELECT COUNT (*) from user";
int queryForInt (String sql)
String sql = "SELECT name from user where id =?";
<T> T queryForObject (String sql, class<t> requiredtype, Object ... args)
4, complex query JdbcTemplate no handler, manual completion of object encapsulation
Writing entity Classes RowMapper
Class Userrowmapper implements Rowmapper<user> {
@Override
Public User Maprow (ResultSet rs, int rowNum) throws SQLException {
RS points to each data, does not need to call next on its own, the RS point to the Data conversion user Object
User user = new user ();
User.setid (Rs.getint ("id"));
User.setname (rs.getstring ("name"));
return user;
}
}
Querying a single object <T> T
queryForObject (String sql, rowmapper<t> rowmapper, Object ... args)
Return This.getjdbctemplate (). queryForObject (SQL, New Userrowmapper (), id);
Query all Objects List collection <T> list<t>
Query (String sql, rowmapper<t> rowmapper, Object ... args)
Return this.getjdbctemplate (). query (SQL, New Userrowmapper ()); Reference Http://www.tuicool.com/articles/nYjEjy Source Download
http://download.csdn.net/detail/sunxiaoyu94/9402507

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.