Spring JDBC Template

本文介绍了如何使用Spring的JDBC模板(JdbcTemplate)进行数据库操作,包括插入、删除、查询和更新。通过示例代码展示了JdbcTemplate在Test类中的应用,并提供了XML配置文件的详细内容,帮助理解数据源和JdbcTemplate的设置。此外,还提到了JdbcTemplate与其他模板类的区别,如NamedParameterJdbcTemplate和SimpleJdbcTemplate。
摘要由CSDN通过智能技术生成

1.Test class :

package com.bcsis.g3.test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

import javax.sql.DataSource;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ConnectionCallback;
import org.springframework.jdbc.core.JdbcTemplate;

public class JDBCTemplateTest {
    
      
        static int addRecord(JdbcTemplate jdbc  ) {  

            jdbc.execute(new ConnectionCallback() {  
      
                public Object doInConnection(Connection con) throws SQLException,  DataAccessException {  
                    String sql = "insert into TEST1(reason,volume, amount) values (?,?,?) ";  
                    PreparedStatement ps = con.prepareStatement(sql,  
                            Statement.RETURN_GENERATED_KEYS);  
                    ps.setString(1, "reason1");  
                    ps.setInt(2, 100);
                    ps.setInt(3, 100);
                    ps.executeUpdate();  
      
//                    ResultSet rs = ps.getGeneratedKeys();  
//                    if (rs.next())  
//                        user.setId(rs.getInt(1));  
                    return null;  
                }  
            });  
            return 0;  
        }  

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        
        ApplicationContext filecontext = new ClassPathXmlApplicationContext("com/bcsis/report/resources/JDBC-config.xml");
        DataSource datasource  =  (DataSource) filecontext.getBean("dataSource");
        System.out.println("datasource : "+datasource);
           
         JdbcTemplate jdbc = new JdbcTemplate(datasource);  
         addRecord(jdbc);
           

    }

}

2. xml config :

1)JDBC-config.xml

<?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.xsd">

  <import resource="datasource.xml" />

  <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    <property name="dataSource" ref="dataSource" />
 </bean>
    
    
</beans>

2.datasource.xml

<?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.xsd">
    
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="${db.driver.classname}" />
        <property name="url" value="${db.connection.url}" />
        <property name="username" value="${db.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>
    
</beans>



Reference1 :  http://lichaozhangobj.iteye.com/blog/700141

jdbcTemplate 例子  

Java代码   收藏代码
  1. public class JdbcTemplateTest {  
  2.   
  3.     static JdbcTemplate jdbc = new JdbcTemplate(JdbcUtils.getDataSource());  
  4.   
  5.     public static void main(String[] args) {  
  6.     }  
  7.   
  8.     static int addUser(final User user) {  
  9.           
  10.         //更灵活的使用connection  
  11.         jdbc.execute(new ConnectionCallback() {  
  12.   
  13.             public Object doInConnection(Connection con) throws SQLException,  
  14.                     DataAccessException {  
  15.                 String sql = "insert into user(name,birthday, money) values (?,?,?) ";  
  16.                 PreparedStatement ps = con.prepareStatement(sql,  
  17.                         Statement.RETURN_GENERATED_KEYS);  
  18.                 ps.setString(1, user.getName());  
  19.                 ps.setDate(2new java.sql.Date(user.getBirthday().getTime()));  
  20.                 ps.setFloat(3, user.getMoney());  
  21.                 ps.executeUpdate();  
  22.   
  23.                 ResultSet rs = ps.getGeneratedKeys();  
  24.                 if (rs.next())  
  25.                     user.setId(rs.getInt(1));  
  26.                 return null;  
  27.             }  
  28.         });  
  29.         return 0;  
  30.     }  
  31.   
  32.     static Map getData(int id) {  
  33.         String sql = "select id as userId, name, money, birthday  from user where id="  
  34.                 + id;  
  35.         return jdbc.queryForMap(sql);  
  36.     }  
  37.   
  38.     static String getUserName(int id) {  
  39.         String sql = "select name from user where id=" + id;  
  40.         Object name = jdbc.queryForObject(sql, String.class);  
  41.         return (String) name;  
  42.     }  
  43.   
  44.     static int getUserCount() {  
  45.         String sql = "select count(*) from user";  
  46.         return jdbc.queryForInt(sql);  
  47.     }  
  48.   
  49.     static List findUsers(int id) {  
  50.         String sql = "select id, name, money, birthday  from user where id<?";  
  51.         Object[] args = new Object[] { id };  
  52.         int[] argTypes = new int[] { Types.INTEGER };  
  53.         List users = jdbc.query(sql, args, argTypes, new BeanPropertyRowMapper(  
  54.                 User.class));  
  55.         return users;  
  56.     }  
  57.   
  58.     static User findUser(String name) {  
  59.         String sql = "select id, name, money, birthday  from user where name=?";  
  60.         Object[] args = new Object[] { name };  
  61.         Object user = jdbc.queryForObject(sql, args, new BeanPropertyRowMapper(  
  62.                 User.class));  
  63.         return (User) user;  
  64.     }  
  65.   
  66.     static User findUser1(String name) {  
  67.         String sql = "select id, name, money, birthday  from user where name=?";  
  68.         Object[] args = new Object[] { name };  
  69.         Object user = jdbc.queryForObject(sql, args, new RowMapper() {  
  70.   
  71.             public Object mapRow(ResultSet rs, int rowNum) throws SQLException {  
  72.                 User user = new User();  
  73.                 user.setId(rs.getInt("id"));  
  74.                 user.setName(rs.getString("name"));  
  75.                 user.setMoney(rs.getFloat("money"));  
  76.                 user.setBirthday(rs.getDate("birthday"));  
  77.                 return user;  
  78.             }  
  79.         });  
  80.         return (User) user;  
  81.     }  
  82. }  

 

Java代码   收藏代码
  1. public class JdbcTemplateTest {  
  2.   
  3.     public static JdbcTemplate jdbcTemplet = new JdbcTemplate(JdbcUtils  
  4.             .getDataSource());  
  5.   
  6.     public static void main(String[] args) {  
  7.     }  
  8.   
  9.     // 查询返回对象类型  
  10.     public static User getUser(String name) {  
  11.         String sql = "select id,name,password from user where name=?";  
  12.         Object[] args = new Object[] { name };  
  13.         Object user = jdbcTemplet.queryForObject(sql, args,  
  14.                 new BeanPropertyRowMapper(User.class));  
  15.         return (User) user;  
  16.     }  
  17.   
  18.     // 查询返回List类型  
  19.     @SuppressWarnings("unchecked")  
  20.     public static List<User> queryUserForList() {  
  21.         String sql = "select id,name,password from user";  
  22.         return jdbcTemplet.query(sql, new BeanPropertyRowMapper(User.class));  
  23.     }  
  24.   
  25.     // 插入  
  26.     public static void insert() {  
  27.         String sql = "insert into user(name,password) values(?,?)";  
  28.         jdbcTemplet.update(sql, new Object[] { "wanger""123456" });  
  29.     }  
  30.   
  31.     // 删除  
  32.     public static void delete(int id) {  
  33.         String sql = "delete from user where id=?";  
  34.         jdbcTemplet.update(sql, new Object[] { 4 });  
  35.     }  
  36.   
  37.     // 更新  
  38.     public static void update(User user) {  
  39.         String sql = "update user set name=?,password=? where id=?";  
  40.         Object[] args = new Object[] { "张三""000000"1 };  
  41.         int[] argTypes = new int[] { Types.VARCHAR, Types.VARCHAR,  
  42.                 Types.INTEGER };  
  43.         jdbcTemplet.update(sql, args, argTypes);  
  44.     }  
  45.   
  46.     // 插入日期类型  
  47.     public static void insert2() {  
  48.         String sql = "insert into date_table(time) values(?)";  
  49.         Date date = new Date();  
  50.         Object[] args = new Object[] { date };  
  51. //      int[] argTypes = new int[] { Types.TIMESTAMP };  
  52. //      jdbcTemplet.update(sql, args, argTypes);  
  53.         jdbcTemplet.update(sql, args);  
  54.     }  
  55. }  


Reference2 :

Spring的JDBC框架能够承担资源管理和异常处理的工作,从而简化我们的JDBC代码,
让我们只需编写从数据库读写数据所必需的代码。Spring把数据访问的样板代码隐藏到模板类之下,
结合Spring的事务管理,可以大大简化我们的代码.

Spring提供了3个模板类:

JdbcTemplate:Spring里最基本的JDBC模板,利用JDBC和简单的索引参数查询提供对数据库的简单访问。
NamedParameterJdbcTemplate:能够在执行查询时把值绑定到SQL里的命名参数,而不是使用索引参数。
SimpleJdbcTemplate:利用Java 5的特性,比如自动装箱、通用(generic)和可变参数列表来简化JDBC模板的使用。
具体使用哪个模板基本上取决于个人喜好。


使用Spring的JdbcTemplate来实现简单的增删改查,首先建立测试数据表person
create table person(
id int not null primary key auto_increment,
name varchar(20) not null
)

导入依赖的jar包,由于测试中数据源使用的是dbcp数据源,需要以下jar包支持:
commons-logging.jar
commons-pool.jar
commons-dbcp.jar
同时还必须导入数据库驱动jar包:mysql-connector-java-3.1.8-bin.jar

建立实体bean
Person.java

Java代码   收藏代码
  1. package com.royzhou.jdbc;  
  2.   
  3. public class PersonBean {  
  4.     private int id;  
  5.     private String name;  
  6.   
  7.     public PersonBean() {  
  8.     }  
  9.       
  10.     public PersonBean(String name) {  
  11.         this.name = name;  
  12.     }  
  13.       
  14.     public PersonBean(int id, String name) {  
  15.         this.id = id;  
  16.         this.name = name;  
  17.     }  
  18.        
  19.     public int getId() {  
  20.         return id;  
  21.     }  
  22.   
  23.     public void setId(int id) {  
  24.         this.id = id;  
  25.     }  
  26.   
  27.     public String getName() {  
  28.         return name;  
  29.     }  
  30.   
  31.     public void setName(String name) {  
  32.         this.name = name;  
  33.     }  
  34.       
  35.     public String toString() {  
  36.         return this.id + ":" + this.name;  
  37.     }  
  38. }  


接口类:
PersonService.java
Java代码   收藏代码
  1. package com.royzhou.jdbc;  
  2.   
  3. import java.util.List;  
  4.   
  5. public interface PersonService {  
  6.       
  7.     public void addPerson(PersonBean person);  
  8.       
  9.     public void updatePerson(PersonBean person);  
  10.       
  11.     public void deletePerson(int id);  
  12.       
  13.     public PersonBean queryPerson(int id);  
  14.       
  15.     public List<PersonBean> queryPersons();  
  16. }  


实现类:
PersonServiceImpl.java
Java代码   收藏代码
  1. package com.royzhou.jdbc;  
  2.   
  3. import java.util.List;  
  4.   
  5. import javax.sql.DataSource;  
  6. import java.sql.Types;  
  7.   
  8. import org.springframework.jdbc.core.JdbcTemplate;  
  9.   
  10. public class PersonServiceImpl implements PersonService {  
  11.   
  12.     private JdbcTemplate jdbcTemplate;  
  13.       
  14.     /** 
  15.      * 通过Spring容器注入datasource 
  16.      * 实例化JdbcTemplate,该类为主要操作数据库的类 
  17.      * @param ds 
  18.      */  
  19.     public void setDataSource(DataSource ds) {  
  20.         this.jdbcTemplate = new JdbcTemplate(ds);  
  21.     }  
  22.       
  23.     public void addPerson(PersonBean person) {  
  24.         /** 
  25.          * 第一个参数为执行sql 
  26.          * 第二个参数为参数数据 
  27.          * 第三个参数为参数类型 
  28.          */  
  29.         jdbcTemplate.update("insert into person values(null,?)"new Object[]{person.getName()}, new int[]{Types.VARCHAR});  
  30.     }  
  31.   
  32.     public void deletePerson(int id) {  
  33.         jdbcTemplate.update("delete from person where id = ?"new Object[]{id}, new int[]{Types.INTEGER});  
  34.     }  
  35.   
  36.     public PersonBean queryPerson(int id) {  
  37.         /** 
  38.          * new PersonRowMapper()是一个实现RowMapper接口的类, 
  39.          * 执行回调,实现mapRow()方法将rs对象转换成PersonBean对象返回 
  40.          */  
  41.         PersonBean pb = (PersonBean) jdbcTemplate.queryForObject("select id,name from person where id = ?"new Object[]{id}, new PersonRowMapper());  
  42.         return pb;  
  43.     }  
  44.   
  45.     @SuppressWarnings("unchecked")  
  46.     public List<PersonBean> queryPersons() {  
  47.         List<PersonBean> pbs = (List<PersonBean>) jdbcTemplate.query("select id,name from person"new PersonRowMapper());  
  48.         return pbs;  
  49.     }  
  50.   
  51.     public void updatePerson(PersonBean person) {  
  52.         jdbcTemplate.update("update person set name = ? where id = ?"new Object[]{person.getName(), person.getId()}, new int[]{Types.VARCHAR, Types.INTEGER});  
  53.     }  
  54. }  


PersonRowMapper.java
Java代码   收藏代码
  1. package com.royzhou.jdbc;  
  2.   
  3. import java.sql.ResultSet;  
  4. import java.sql.SQLException;  
  5.   
  6. import org.springframework.jdbc.core.RowMapper;  
  7.   
  8. public class PersonRowMapper implements RowMapper {  
  9.     //默认已经执行rs.next(),可以直接取数据  
  10.     public Object mapRow(ResultSet rs, int index) throws SQLException {  
  11.         PersonBean pb = new PersonBean(rs.getInt("id"),rs.getString("name"));  
  12.         return pb;  
  13.     }  
  14. }  


我们需要在bean.xml中配置DataSource,并且将datasource注入到我们的业务类中

Xml代码   收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.        xmlns:context="http://www.springframework.org/schema/context"   
  5.        xmlns:aop="http://www.springframework.org/schema/aop"  
  6.        xsi:schemaLocation="http://www.springframework.org/schema/beans  
  7.            http://www.springframework.org/schema/beans/spring-beans-2.5.xsd  
  8.            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd  
  9.            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">  
  10.   
  11.      <context:property-placeholder location="classpath:jdbc.properties"/>  
  12.      <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">  
  13.         <property name="driverClassName" value="${driverClassName}"/>  
  14.         <property name="url" value="${url}"/>  
  15.         <property name="username" value="${username}"/>  
  16.         <property name="password" value="${password}"/>  
  17.          <!-- 连接池启动时的初始值 -->  
  18.          <property name="initialSize" value="${initialSize}"/>  
  19.          <!-- 连接池的最大值 -->  
  20.          <property name="maxActive" value="${maxActive}"/>  
  21.          <!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->  
  22.          <property name="maxIdle" value="${maxIdle}"/>  
  23.          <!--  最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->  
  24.          <property name="minIdle" value="${minIdle}"/>  
  25.      </bean>  
  26.       
  27. </beans>  


jdbc.properties
Java代码   收藏代码
  1. driverClassName=org.gjt.mm.mysql.Driver  
  2. url=jdbc:mysql://localhost:3306/royzhou?useUnicode=true&characterEncoding=UTF-8  
  3. username=root  
  4. password=123456  
  5. initialSize=1  
  6. maxActive=500  
  7. maxIdle=2  
  8. minIdle=1  


编写我们的测试类:TestJdbcTemplate.java
Java代码   收藏代码
  1. package com.royzhou.
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值