spring JdbcTemplate
来源:互联网 发布:《大数据思维与决策》 编辑:程序博客网 时间:2024/06/16 06:01
1 概述
可以将Spring的JdbcTemplate看作是一个小型的轻量级持久化层框架,和我们之前使用过的DBUtils风格非常接近。
2 配置环境及测试实验:
2.1 导入JAR包
①IOC容器所需要的JAR包
commons-logging-1.1.1.jar
spring-beans-4.0.0.RELEASE.jar
spring-context-4.0.0.RELEASE.jar
spring-core-4.0.0.RELEASE.jar
spring-expression-4.0.0.RELEASE.jar
②JdbcTemplate所需要的JAR包
spring-jdbc-4.0.0.RELEASE.jar
spring-orm-4.0.0.RELEASE.jar
spring-tx-4.0.0.RELEASE.jar
③数据库驱动和数据源
c3p0-0.9.1.2.jar
mysql-connector-java-5.1.7-bin.jar
④如果需要AOP的话,导入AOP相关加包就可以啦。
2.2 创建连接数据库基本信息属性文件
在IOC容器中配置数据源:jdbc.properties
jdbc.username=rootjdbc.password=123456jdbc.jdbcUrl=jdbc:mysql:///jdbc_templatejdbc.driverClass=com.mysql.jdbc.Driverjdbc.initialPoolSize=30jdbc.minPoolSize=10jdbc.maxPoolSize=100jdbc.acquireIncrement=5jdbc.maxStatements=1000jdbc.maxStatementsPerConnection=10
2.3 在Spring配置文件中配置相关的bean
<?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: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/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <!-- 加载外部资源文件 --> <context:property-placeholder location="classpath:jdbc.properties"/> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="user" value="${jdbc.user}"/> <property name="password" value="${jdbc.password}"/> <property name="jdbcUrl" value="${jdbc.jdbcUrl}"/> <property name="driverClass" value="${jdbc.driverClass}"/> <property name="initialPoolSize" value="${jdbc.initialPoolSize}"/> <property name="minPoolSize" value="${jdbc.minPoolSize}"/> <property name="maxPoolSize" value="${jdbc.maxPoolSize}"/> <property name="acquireIncrement" value="${jdbc.acquireIncrement}"/> <property name="maxStatements" value="${jdbc.maxStatements}"/> <property name="maxStatementsPerConnection" value="${jdbc.maxStatementsPerConnection}"/> </bean> <!-- 声明jdbcTemplate对象 --> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 配置可以使用具名参数的JDBCTemplate类对象,一般不用--> <bean id="namedTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate"> <!-- 没有无参构造器,必须传入数据源或JdbcTemplate对象 --> <constructor-arg ref="jdbcTemplate"/> </bean></beans>
2.4 创建表结构:
USE jdbc_template;DROP TABLE IF EXISTS employee;CREATE TABLE employee ( emp_id INT(11) NOT NULL AUTO_INCREMENT, emp_name CHAR(100) DEFAULT NULL, salary DOUBLE DEFAULT NULL, PRIMARY KEY (emp_id)) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;INSERT INTO employee(emp_id,emp_name,salary) VALUES (1,'Susan',5000.23),(2,'Julian',4234.77),(3,'Papu',9034.51),(4,'Babala',8054.33),(5,'Kasier',6039.11),(6,'Owen',7714.11);
2.5 创建实体类
package com.atguigu.jdbc.entity;public class Employee {private Integer empId;private String empName;private double salary;// get/set}
2.6 创建测试类
package junit.test;import java.sql.Connection;import java.sql.SQLException;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import javax.sql.DataSource;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import org.springframework.jdbc.core.BeanPropertyRowMapper;import org.springframework.jdbc.core.JdbcTemplate;import org.springframework.jdbc.core.RowMapper;import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;import org.springframework.jdbc.core.namedparam.SqlParameterSource;import com.atguigu.spring.dao.EmployeeDao;import com.atguigu.spring.jdbc.bean.Employee;public class TestJdbcTemplate { ApplicationContext ioc = new ClassPathXmlApplicationContext("beans.xml" ); JdbcTemplate template = (JdbcTemplate)ioc.getBean("jdbcTemplate" ); NamedParameterJdbcTemplate namedParameterJdbcTemplate = (NamedParameterJdbcTemplate)ioc .getBean("namedParameterJdbcTemplate"); @Test public void testDataSource() throws SQLException { //实验1:测试数据源 DataSource dataSource = ioc.getBean(DataSource.class); Connection connection = dataSource.getConnection(); System. out.println(connection); connection.close(); //归还到连接池 } @Test public void test01(){ //实验2:将emp_id=5的记录的salary字段更新为1300.00 String sql = "UPDATE employee SET salary=? WHERE emp_id=?"; template.update(sql, 1300.0, 5); } @Test public void test02(){ //实验3:批量插入 String sql = "INSERT INTO employee(emp_name,salary) VALUES(?,?)"; List<Object[]> batchArgs = new ArrayList<Object[]>(); batchArgs.add( new Object[]{"a" ,1000.0}); batchArgs.add( new Object[]{"b" ,2000.0}); batchArgs.add( new Object[]{"c" ,3000.0}); template.batchUpdate(sql, batchArgs); } @Test public void test03(){ //实验4:查询emp_id=5的数据库记录,封装为一个Java对象返回 String sql = "SELECT emp_id as empId,salary,emp_name empName FROM employee WHERE emp_id=?"; RowMapper<Employee> rowMapper = new BeanPropertyRowMapper<Employee>(Employee.class) ; Employee employee = template.queryForObject(sql, rowMapper, 5); System. out.println(employee); } @Test public void test04(){ //实验5:查询salary>4000的数据库记录,封装为List集合返回 String sql = "SELECT emp_id as empId,salary,emp_name empName FROM employee WHERE salary>?"; RowMapper<Employee> rowMapper = new BeanPropertyRowMapper<Employee>(Employee.class) ; List<Employee> empList = template.query(sql, rowMapper, 4000.0); for (Employee employee : empList) { System. out.println(employee); } } @Test public void test05(){ //实验6:查询最大salary String sql = "SELECT MAX(salary) FROM employee "; double maxSalary = template .queryForObject(sql, Double.class ); System. out.println(maxSalary); } @Test public void test06(){ //实验7:使用带有具名参数的SQL语句插入一条员工记录,并以Map形式传入参数值 String sql = "INSERT INTO employee(emp_name,salary) VALUES(:paramName,:paramSalary)"; Map<String,Object> paramMap = new HashMap<String,Object>(); paramMap.put( "paramName", "TOM2016" ); paramMap.put( "paramSalary", 50000); //namedParameterJdbcTemplate.update( sql, paramMap); } @Test public void test07(){ //实验8:重复实验7,以SqlParameterSource形式传入参数值,具名参数的名称需要跟数据模型对象的属性名称一致。 String sql = "INSERT INTO employee(emp_name,salary) VALUES(:empName,:salary)"; Employee employee = new Employee(); employee.setEmpName( "TOM2030"); employee.setSalary(600000); SqlParameterSource paramSource = new BeanPropertySqlParameterSource(employee) ; namedParameterJdbcTemplate.update(sql, paramSource); } @Test public void test08(){ //实验9:创建EmployeeDao,自动装配JdbcTemplate对象 EmployeeDao dao = ioc.getBean(EmployeeDao.class); dao.save( "Kete",50000); }}
3.JdbcTemplate常用方法总结:
execute方法:可以用于执行任何SQL语句,一般用于执行DDL语句;update方法及batchUpdate方法:update方法用于执行新增、修改、删除等语句;batchUpdate方法用于执行批处理相关语句;query方法及queryForXXX方法:用于执行查询相关语句;call方法:用于执行存储过程、函数相关语句。
说明(如果进一步详细学习请看 ):http://blog.csdn.net/gjswxhb/article/details/8586198
阅读全文
1 0
- spring JdbcTemplate
- spring jdbcTemplate
- Spring JdbcTemplate
- Spring JDBCTemplate
- Spring jdbctemplate
- spring JdbcTemplate
- spring jdbcTemplate
- Spring JDBCTemplate
- spring jdbctemplate
- spring jdbctemplate
- Spring JdbcTemplate
- Spring--JdbcTemplate
- spring jdbcTemplate
- Spring jdbcTemplate
- spring-jdbcTemplate
- Spring JdbcTemplate
- spring jdbcTemplate
- Spring JdbcTemplate
- Ajax
- codevs 1036 商务旅行 LCA 解题报告
- LinkedList
- NLP深度学习 —— CS224学习笔记6
- Linux网络编程——UDP服务器和广播/组播
- spring JdbcTemplate
- Linux中chown和chmod的区别和用法
- Linux——系统分区之分区与格式化
- html5可缩放时钟
- C++模拟ATM
- Linux使用笔记
- 1002. A+B for Polynomials (25)
- openjudge 6256 带通配符的字符串匹配(动态规划)
- Linux网络编程——I/O多路复用