一、整合的步骤

  1、步骤一:首先要获得DataSource连接池(推荐使用B方式):
要对数据库执行任何的JDBC操作,需要有一个Connection.在Spring中,Connection对象是通过DataSource获得的。

有几种方法可以得到DataSource,
其中一种方法是使用Spring提供的轻量级
org.springframework.jdbc.datasource.DriverManagerDataSource,第二种方法是使用
org.apache.commons.dbcp.BasicDataSource类。

A:使用DriverMangerDataSource获取DataSource,这种方法是轻量级的,方便测试
    public class
DataSoureProvider {
    
public static DriverManagerDataSource dataSource = new
DriverManagerDataSource();
 
    
public static DriverManagerDataSource getInstance() {
        
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        
dataSource.setUrl("jdbc:mysql://localhost:3306/book");
        
dataSource.setUsername("y****");
        
dataSource.setPassword("h*******");
        
return dataSource;
    
}
 
    
@Test
    
public void test() {
        
DataSoureProvider.getInstance();
        
try {
            
dataSource.getConnection();
        
}
        
catch (SQLException e) {
            
e.printStackTrace();
        
}
    
}
 }

 
B:通过使用BasicDataSouce创建一个连接池
获取DataSource。应为BasicDataSource所有属性都是通过setter方法暴露在外面的,我们可以像配置其他Srping
Bean那样配置它我将数据库连接信息配置在properties文件中,利用spring的org.springframeword.beans.factory.config.PropertyPlaceholderConfigurer类进行读取装载。

注意:
使用org.apache.commons.dbcp.BasicDataSource需要引入额外的jar包,分别是,commons-dbcp-1.4.jar,commons-pool-1.2.jar
(官网下载页面:
http://commons.apache.org/) 

书写配置文件applicationContext.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"
    
xmlns:p="http://www.springframework.org/schema/p"
    
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

<bean id="dbproperty"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

<property
name="location">
            
<!-- 此位置是相对于:部署后的项目的根路径
   
   
   
  <value>/WEB-INF/connect.properties</value>
-->
  
         
<!-- 此位置是相对于:部署后的项目的类路径
-->

             
<value>connect.properties</value>

</property>
    
</bean>
    
<--
配置BasicDataSource参数,其中<value>中的参数是在connect.propertices配置文件
中拿到的,其实value值也可以直接写上的-->
    
<bean id="myDataSource"
class="org.apache.commons.dbcp.BasicDataSource">

<property
name="driverClassName">
            
<value>${db.driver}</value>

</property>
        
<property name="url">
            
<value>${db.url}</value>

</property>
        
<property name="username">
            
<value>${db.username}</value>

</property>
        
<property name="password">
            
<value>${db.password}</value>

</property>
    
</bean>

 </beans>

--------------------------------------------------------------------------------------

 
2、步骤二:使用JdbcTemplate类操作数据库:

   
Spring把JDBC中重复的操作建立成了一个模板类:org.springframework.jdbc.core.JdbcTemplate。

  
A:要使用JdbcTemplate,需要为每一个DAO配置一个JdbcTemplate实例:

  public class StudentDaoImp implements StudentDao
{
    
private JdbcTemplate jdbcTemplate;
 
    
@Override
    
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        
this.jdbcTemplate = jdbcTemplate;
    
}
 }
 
B:如上,StudentDaoImp内配置了一个JdbcTemplate对象和它对应的setter方法。这样就可以在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"
xmlns:p="http://www.springframework.org/schema/p"
    
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

<bean id="dbproperty"
        
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

<property name="location">
            
<value>connect.properties</value>

</property>
    
</bean>
 
    
<bean id="myDataSource"
class="org.apache.commons.dbcp.BasicDataSource">

<property
name="driverClassName">
            
<value>${db.driver}</value>

</property>
        
<property name="url">
            
<value>${db.url}</value>

</property>
        
<property name="username">
            
<value>${db.username}</value>

</property>
        
<property name="password">
            
<value>${db.password}</value>

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

<constructor-arg
ref="
myDataSource"></constructor-arg>

</bean>

<bean id="studentDao"
class="com.sunflower.dao.StudentDaoImp">
        
<property name="jdbcTemplate">
            
<ref bean="jdbcTemplate"/>
        
</property>
    
</bean>
 </beans>
  C:使用JdbcTemplate插入数据:
   

  
1)插入单条数据:JdbcTemplate为我们提供了update(String sql,Object...
args)方法,方便我们进行数据的插入.
 
 
2)批量添加数据:
批量插入数据需要用到org.springframework.jdbc.core.BatchPreparedStatementSetter接口。BatchPreparedStatementSetter接口的两个方法,其中getBatchSize()方法是得到需要插入的记录的个数,setValues(PreparedStatement
ps, int index)
方法是实际进行插入的方法。
 
3)查询单条记录:
执行一条数据的查询,需要使用org.springframework.jdbc.core.RowCallbackHandler接口的实现。

4)查询多条记录:这里需要用到org.springframework.jdbc.core.RowMapper接口的实现。RowMapper接口负责把Result中的一条记录映射成一个对象。

public class StudentDaoImp implements
StudentDao {
    
private JdbcTemplate jdbcTemplate;
 
    
@Override
    
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        
this.jdbcTemplate = jdbcTemplate;
    
}
    
//插入单条数据
    
public void insert(Student student)
    
{
        
String sql = "insert into student (cno,name,score)
values(?,?,?)";
        
//设置传递给通配符的参数
        
Object[] params = new Object[]{student.getCno(), student.getName(),
student.getScore()};
        
jdbcTemplate.update(sql, params);

    
}
    
//批量插入数据
    public int[]
batchInsert(final List<Student>
list)
    
{
        
String sql = "insert into student (cno,name,score)
values(?,?,?)";

BatchPreparedStatementSetter setter = new
BatchPreparedStatementSetter() {

@Override
            
public void setValues(PreparedStatement ps, int index) throws
SQLException {
                
Student student = (Student) list.get(index);
                
ps.setInt(1, student.getCno());
                
ps.setString(2, student.getName());
                
ps.setDouble(3, student.getScore());
            
}

//有多少条记录要处理
            
@Override
            
public int getBatchSize() {
                
return list.size();
            
}

        
};

return jdbcTemplate.batchUpdate(sql, setter);
    
}
    
//查询单条记录

  
    
public Student getStudent(final int id) {
        
// 装载查询结果
        
final Student student = new Student();
 
        
String sql = "select s.cno,s.name,s.score from student s where sno
= ?";
        
// 设置查询参数
        
final Object[] params = new Object[] { new Integer(id) };
        
// 进行查询
        
jdbcTemplate.query(sql, params,
new RowCallbackHandler() {
            
@Override
            
public void processRow(ResultSet rs) throws SQLException {
                
student.setCno(rs.getInt("cno"));
                
student.setName(rs.getString("name"));
                
student.setScore(rs.getDouble("score"));
            
}
        
});

return student;
    
}

//查询多条记录
   
    
public List<Student> getAllStudent()
{
        
String sql = "select s.cno,s.name,s.score from student s";
 
        
return jdbcTemplate.query(sql,
new
RowMapper<Student>() {
            
@Override
            
public Student mapRow(ResultSet rs, int index) throws SQLException
{
                
Student student = new Student();
                
student.setCno(rs.getInt("cno"));
                
student.setName(rs.getString("name"));
                
student.setScore(rs.getDouble("score"));
 
                
return student;
            
}
        
});

    
}

}

另附:也可以使用org.springframework.jdbc.core.RowMapper接口查询一条记录,只要附加查询参数即可:

public Student getStudent(final int id) {
        
// 装载查询结果
        
final Student student = new Student();
 
        
String sql = "select s.cno,s.name,s.score from student s where sno
= ?";
        
// 设置查询参数
        
final Object[] params = new Object[] { new Integer(id) };
 
        
List<Student> list = jdbcTemplate.query(sql, params,
                
new
RowMapper<Student>() {
                    
@Override
                    
public Student mapRow(ResultSet rs, int index)
                            
throws SQLException {
                        
Student student = new Student();
                        
student.setCno(rs.getInt("cno"));
                        
student.setName(rs.getString("name"));
                        
student.setScore(rs.getDouble("score"));
 
                        
return student;
                    
}
                
});

return list.get(0);
    
}

二、采用注解方式配置事务处理
   1、在Spring配置文件beans元素中添加子元素:
 
<!– 声明事务管理器
-->

<bean
id="txManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

<property name="dataSource"
ref="dataSource"/>
  </bean>
 <!–
采用@Transactional注解方式使用事务  -->
  <tx:annotation-driven
transaction-manager="txManager"/>

 
2、在业务逻辑的试下类中使用注解添加相应的事务

   @Service @Transactional
public class StudentServiceBean implements StudentService {
@Transactional(类型=值)
public void add(Student stu) {
   
dao.insert(stu);
}
}

Spring学习5-Spring整合JDBC及其事务处理(注解方式)的更多相关文章

  1. 【Spring学习笔记-MVC-4】SpringMVC返回Json数据-方式2

    <Spring学习笔记-MVC>系列文章,讲解返回json数据的文章共有3篇,分别为: [Spring学习笔记-MVC-3]SpringMVC返回Json数据-方式1:http://www ...

  2. 【Spring学习笔记-MVC-3】SpringMVC返回Json数据-方式1

    <Spring学习笔记-MVC>系列文章,讲解返回json数据的文章共有3篇,分别为: [Spring学习笔记-MVC-3]SpringMVC返回Json数据-方式1:http://www ...

  3. Spring学习(十一)-----Spring使用@Required注解依赖检查

    Spring学习(九)-----Spring依赖检查 bean 配置文件用于确定的特定类型(基本,集合或对象)的所有属性被设置.在大多数情况下,你只需要确保特定属性已经设置但不是所有属性.. 对于这种 ...

  4. Spring学习(六)-----Spring使用@Autowired注解自动装配

    Spring使用@Autowired注解自动装配 在上一篇 Spring学习(三)-----Spring自动装配Beans示例中,它会匹配当前Spring容器任何bean的属性自动装配.在大多数情况下 ...

  5. (转)Spring使用AspectJ进行AOP的开发:注解方式

    http://blog.csdn.net/yerenyuan_pku/article/details/69790950 Spring使用AspectJ进行AOP的开发:注解方式 之前我已讲过Sprin ...

  6. Spring整合JDBC及事务处理

    1.Spring整合JDBC DAO是数据访问对象(data access object)的简写.接口是实现松耦合的关键,Spring也鼓励使用接口,但不是强制的. 捕获异常时希望能尝试从异常状态中恢 ...

  7. spring学习 六 spring与mybatis整合

    在mybatis学习中有两种配置文件 :全局配置文件,映射配置文件.mybatis和spring整合,其实就是把mybatis中的全局配置文件的配置内容都变成一个spring容器的一个bean,让sp ...

  8. Spring学习之Spring与Mybatis的两种整合方式

    本机使用IDEA 2020.1.MySql 8.0.19,通过Maven进行构建 环境准备 导入maven依赖包 <dependencies> <dependency> < ...

  9. spring学习07(整合MyBatis)

    10.整合MyBatis 10.1 相关jar包 junit <dependency> <groupId>junit</groupId> <artifactI ...

随机推荐

  1. UI设计师零基础入门到精通精品视频教程【155课高清完整版】

    [福吧资源网分享]课程是非常完整的,也是非常零基础的,适合任何学员,有需要的可以下载看看!课程目录:第1章 Adobe Photoshop CS6课时1 Adobe Photoshop CS6入门基础 ...

  2. 10个鲜为人知的WordPress函数

    WordPress功能强大,非常适合开发者使用.说到 WordPress,那么,我们不得不说他的钩子函数.今天,要为大家推荐10个WordPress函数.大多数,都是我们常用的功能,不过,经常不知道如 ...

  3. 第十章 系统级I/O

    第十章 系统级I/O 一.Unix I/O 1.一个unix文件就是一个m个字节的序列 2.unix外壳创建的每个进程开始时都有三个打开的文件:标准输入(0) .标准输出(1)和标准错误(-1). 二 ...

  4. Linux第14周学习笔记

    虚拟存储器 虚拟存储器是硬件异常.硬件地址翻译.主存.磁盘文件和内核软件的完美交互. 虚拟存储器的特点: 中心的 强大的 危险的 物理和虚拟寻址 计算机系统的主存被组织成一个由M个连续的字节大小的单元 ...

  5. Cannot Change Opencv Webcam Setting

    I have encountered a problem that when I use opencv API, I cannot change the width and height of Web ...

  6. mvc Areas注册域常见问题一

    添加Areas主要目的是区分一些不同的业务,避免不同的业务都在同一个Controllers下造成混乱,在MVC项目上右键->添加区域->我添加了HMbolie和PClient两个区域-&g ...

  7. STM32的USB速度,终于确定了传输极限,为以后的产品设计提供了数据。

    是自定协议,用到一个bulk in ep1, 一个bulk out ep2 端点  用虚拟串口的优点显而易见,上位机的编写非常方便,就按照常规的串口功能编写就可以了,而速度确还是usb的速度  USB ...

  8. ORA-00911: 无效字符

    思路:遇到这样问题首先第一步:将有误sql粘至数据库运行一下,如果报错,说明sql存在问题. 第二步:数据库没问题.那么就要想你的书写方式是否正确,是否是ibatasi里的写法,或许是多了个 :  或 ...

  9. 云计算之路-阿里云上:2014年6月11日17点遇到的CPU 100%状况

    今天下午17:00-17:05之间,在请求量没有明显变化的情况下,SLB中的1台云服务器的CPU突然串到100%(当时SLB中一共有3台云服务器),见下图: 造成的直接后果是请求执行时间变得超长,最长 ...

  10. js验证身份证号

    /* * 身份证检测(格式.地区.生日.年龄范围) * code:检测字符串 rangeAge:年龄范围[格式为:25-55] * 返回值 0:为空 ,不为0则验证不通过 */ : : : : : : ...