spring整合JdbcTemplate

5 篇文章 0 订阅

JdbcTemplate是spring框架中提供的一个对象,是对Jdbc API对象的简单封装。

/*
 * update()方法用于插入、更新和删除操作;
 * 他有两个参数,String sql:要执行的SQL语句,
 * 该SQL语句可以有占位符,占位符用"?"代替。
 * 查询数据时,常使用query()方法,
 * 他有两个或三个参数,
 * String sql:要执行的SQL语句,
 * ;
 * 在查询的结果为多条时,使用该参数,该参数最常用,
 * 因为他就可以查询单条结果,有可以查询多条结果;
 * 并且RowMapper的BeanPropertyRowMapper子类提供了自动封装对象功能,
 * 当类对象的属性与数据库中的字段名称一致时,可以指定将结果集中的数据封装成类对象。
 * ResultSetExtractor<T> rse:将查询的单条结果封装成对象;
 * 该参数不经常使用,因为他的子类没有提供自动封装对象的类,使用时,
 * 要自己定义。
 * 第三个参数是SQL语句中的占位符。
 * 

JdbcTemplate的单独使用

import java.util.List;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.yuxiang.pojo.Account;
/**
 * jdbcTemplate基本连接操作
 * @author Administrator
 *
 */
public class JdbcTemplateDemo {
	
	public static void main(String[] args) throws Exception {			
			//配置数据库
			ComboPooledDataSource ds = new ComboPooledDataSource();
			ds.setDriverClass("com.mysql.jdbc.Driver");
			ds.setJdbcUrl("jdbc:mysql://localhost:3306/test");
			ds.setUser("root");
			ds.setPassword("root");
			//获取JdbcTemplate对象
			JdbcTemplate jt = new JdbcTemplate();
			//给jdbctemplate设置数据库
			jt.setDataSource(ds);
			//调用方法操作
			jt.update("insert into account(id,name,money) values(?,?,?)",1,"张三",1000);
	}

 }

JdbcTemplate对象中最常用的两个方法是update()、query()和queryForObject()方法。其中数据的增、删、该操作使用update()方法;该方法有两个参数,String sql(要执行的SQL语句)和Object…args(占位符对应的参数值)。查询数据时,使用query()方法;该方法的参数有String sql(要执行的SQL语句)、RowMapper rowMapper(将查询的结果集中的数据,一条一条集封成类对象,RowMapper 是一个借口,需要自己定义一个类实现该接口,在类中定义如何将数据封装成已有的对象;但是当对象中的各属性名与数据库中的各字段名一致时,可以使用RowMapper的BeanPropertyRowMapper子类提供了自动封装对象)和Object…args(占位符对应的参数值)。queryForObject()方法是用于返回一行一列查询;他的参数有String sql(要执行的SQL语句)和返回值的类型字节码。

public class Account {
	private Integer id;
	private String name;
	private Float money;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Float getMoney() {
		return money;
	}
	public void setMoney(Float money) {
		this.money = money;
	}
	public Account(Integer id, String name, Float money) {
		super();
		this.id = id;
		this.name = name;
		this.money = money;
	}
	
	public Account() {
		super();
		
	}
	@Override
	public String toString() {
		return "Account [id=" + id + ", name=" + name + ", money=" + money + "]";
	}
}
import java.beans.PropertyVetoException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.RowMapperResultSetExtractor;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.yuxiang.pojo.Account;
/*
 * update()方法用于插入、更新和删除操作;
 * 他有两个参数,String sql:要执行的SQL语句,
 * 该SQL语句可以有占位符,占位符用"?"代替。
 * 查询数据时,常使用query()方法,
 * 他有两个或三个参数,
 * String sql:要执行的SQL语句,
 * RowMapper<T> rowMapper:将查询的多条结果,一条一条集封成类对象;
 * 在查询的结果为多条时,使用该参数,该参数最常用,
 * 因为他即可以查询单条结果,又可以查询多条结果;
 * 并且RowMapper的BeanPropertyRowMapper子类提供了自动封装对象功能,
 * 当类对象的属性与数据库中的字段名称一致时,可以指定将结果集中的数据封装成类对象。
 * ResultSetExtractor<T> rse:将查询的单条结果封装成对象;
 * 该参数不经常使用,因为他的子类没有提供自动封装对象的类,使用时,
 * 要自己定义。
 * 第三个参数是SQL语句中的占位符。
 */

public class JdbcTemplateDemo3 {
	
	public static void main(String[] args) throws Exception {
		
		//获取容器
		ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
		//获取对象
		JdbcTemplate jdbcTemplate = ac.getBean("jdbcTemplate",JdbcTemplate.class);
		//插入
//		jdbcTemplate.update("insert into account values(?,?,?)",3,"王五",3000 );
		
		//更新
//		jdbcTemplate.update("update account set name=?,money=? where id=?","李四",2000,2);
		//删除
//		jdbcTemplate.update("delete from account where id = ?",3);
		/*
		 *查询所有操作,AccountRowMapper()是一个实现了RowMapper接口,
		 *在AccountRowMapper()类定义了如何将结果集中的数据封装到已有的对象中
		/*
		List<Account> list = jdbcTemplate.query("select * from account",new AccountRowMapper());
		for(Account account:list){
			System.out.println(account);
			
		}
		*/
		/*
		 *由于Account对象中的各属性名与数据库中的各字段名一致,
		 *所以可以使用BeanPropertyRowMapper(Account.class)来自动将
		 *结果集中的数据封装到Account对象中
		 */
		List<Account> list = jdbcTemplate.query("select * from account where id = ? and name = ?",new BeanPropertyRowMapper(Account.class),1,"张三");
		for(Account account:list){
			System.out.println(account);			
		}
		
		/*
		 *查询一个,AccountResultSetExtractor()是一个实现了ResultSetExtractor接口,
		 *在AccountResultSetExtractor()类定义了如何将结果集中唯一的
		 *数据封装到已有的对象中
		*/
		Account account = jdbcTemplate.query("select * from account where id = ?",new AccountResultSetExtractor(),1);
		System.out.println(account);
		/**
		 * 查询返回一行一列,当SQL语句使用聚合函数,
		 * 并且没有group by子句时,换回的结果就是一行一列
		 */
		Integer unm = jdbcTemplate.queryForObject("select count(*) from account", Integer.class);
		System.out.println(unm);
		
	}

}

class AccountResultSetExtractor implements ResultSetExtractor<Account>{

	@Override
	public Account extractData(ResultSet rs) throws SQLException, DataAccessException {
		Account account  = new Account();
		if(rs.next()){
			account.setId(rs.getInt("id"));
			account.setName(rs.getString("name"));
			account.setMoney(rs.getFloat("money"));
			return account;
		}
		return null;
	}
	
}
class AccountRowMapper implements RowMapper<Account>{

	@Override
	public Account mapRow(ResultSet rs, int rowNum) throws SQLException {
		Account account = new Account();
		account.setId(rs.getInt("id"));
		account.setName(rs.getString("name"));
		account.setMoney(rs.getFloat("money"));	
		return account;
	}
	
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	   xmlns:aop="http://www.springframework.org/schema/aop" 
	   xmlns:tx="http://www.springframework.org/schema/tx" 
	   xmlns:context="http://www.springframework.org/schema/context" 
	   xsi:schemaLocation="http://www.springframework.org/schema/beans 
						   http://www.springframework.org/schema/beans/spring-beans.xsd
						   http://www.springframework.org/schema/aop 
						   http://www.springframework.org/schema/aop/spring-aop.xsd
						   http://www.springframework.org/schema/tx 
						   http://www.springframework.org/schema/tx/spring-tx.xsd
						   http://www.springframework.org/schema/context 
						   http://www.springframework.org/schema/context/spring-context.xsd">
		
		<!-- 配置jdbc操作模板,必须为JdbcTemplate注入一个数据源,
					并且数据源的"name"必须为"dataSource",
					因为在JdbcTemplate类中数据源属性的名称就dataSource,
					如果写成其他的,注入失败 -->
		<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
			<property name="dataSource" ref="dataSource"></property>
		</bean>
		
		
		<!-- 引入外部配置文件 -->
	<context:property-placeholder location="dbconfig.properties" />
		<!-- 配置数据源 -->
		<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" >
			<property name="driverClass" value="${jdbc.driverClass}"></property>
			<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
			<property name="user" value="${jdbc.user}"></property>
			<property name="password" value="${jdbc.password}"></property>
		</bean>
</beans>

dbconfig.properties文件的内容

jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
jdbc.user=root
jdbc.password=root
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值