spring学习之三 数据库操做jdbcTemplate

概念mysql

  jdbcTemplate就Spring对数据库持久化技术的实现,经过它能够对数据库进行CRUD等操做。spring

JDBCTemplate和代码实现sql

public void jdbcadd() {
                DriverManagerDataSource dataSource = new DriverManagerDataSource();
                //加载数据库驱动
                dataSource.setDriverClassName("com.mysql.jdbc.Driver");
                dataSource.setUrl("jdbc:mysql:///dbname");
                dataSource.setUsername("root");
                dataSource.setPassword("123");

                //设置数据源
                JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
                String sql = "insert into user values(?,?)";
                jdbcTemplate.update(sql,"blue", 123);
        }
}

底层JDBC实现代码数据库

public void jdbcimpl() {
                Connection conn = null;
                PreparedStatement ps = null;
                ResultSet rs = null;

                try {
                        Class.forName("com.mysql.jdbc.Driver");
                        conn = DriverManager.getConnection("jdbc:mysql:///dbname", "root", "123");
                        String sql = "select * from user  WHERE  name=?";
                        ps = conn.prepareStatement(sql);
                        ps.setString(1, "blueto");
                        rs = ps.executeQuery();  //执行
                        while (rs.next()) {
                                String name = rs.getString("username");
                                User user = new User();
                                user.setName(name);
                        }

                } catch (Exception e) {
                        e.printStackTrace();
                }
        }

spring 链接池配置express

  c3p0的链接池代码是怎么样实现的呢?红色部分为与前面第一种方式不一样的部分框架

public void c3p0impl(){
                ComboPooledDataSource dataSource = new ComboPooledDataSource();
                //加载数据库驱动
                dataSource.setDriverClassName("com.mysql.jdbc.Driver");
                dataSource.setJdbcUrl("jdbc:mysql:///dbname");
                dataSource.setUser("root");                 dataSource.setPassword("123");

                //设置数据源
                JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
                String sql = "insert into user values(?,?)";
                jdbcTemplate.update(sql, "blue", 123);
        }

  实际的spring项目开发中,是不会像前面那样建立数据库链接conn再去请求执行sql语句的,而是在配置文件中配置好链接池。url

  从代码的实现步骤来看,能够总结 出链接池的执行步骤:spa

  第一步 建立链接池的ComboPooledDataSource 对象hibernate

  第二步 将数据库的驱动,url,用户,密码做为属性注入到Datasource对象中code

  好了,如今再按上面的步骤在配置文件中配置就能够了,如今应该明白别人那样配置了吧,配置文件可写成这样

<?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="com.mchange.v2.c3p0.ComboPooledDataSource">
                <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
                <property name="jdbcUrl" value="jdbc:mysql:///dbname"></property>
                <property name="user" value="root"></property>
                <property name="password" value="123"></property>
        </bean>

</beans>

注意:若是新建一个userDao类去访问数据库的话,因为在访问时须要jdbcTemplate对象

  JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

因此,还须要在配置文件中把建立jdbcTemplate的对象配置配好,并注入dataSource属性。

 数据库的事务管理

  spring 为不一样的持久化框架提供了不一样的事务管理器的接口,共有如下几种类型

  1)org.springframework.jdbc.datasource.DataSourceTransactionManager  -- 用spring jdbc或ibatis进行持久化时用

  2)org.springframework.orm.hibernate5.HibernateTransactionManager  --用于hibernate5版本

  3)org.springframework.orm.jpa.jpaTransactionManager  --用于jpa持久化

  4)org.springframework.transaction.jta.jtaTransactionManager  --JTA管理事务时,在一个事务跨越多个资源时必须使用

  在进行数据库修改操做时,常常被谈及到事务这个概念,那什么叫事务呢?事务就是指一系列的数据库操做的组合,单次对数据表的增删改查为一次操做,只有事务中全部的操做指令所有执行成功,事务才算成功,不然就算失败;若是事务失败,则在事务中已经成功的操做,通通执行回滚操做至事务执行前的状态。

  为何事务失败须要回滚,就拿举例最多的银行转账事件来做为例子吧。

  在转账过程当中,A向B转1000元,首先系统从账户表里用户A的account里的钱减去1000元,再给B的account里加上1000元,至此整个转账事务成功。可是在A的account里减去1000成功后,在往B账号里执行增长1000元的操做时,系统异常退出了,你会发现,A的钱扣了,可是B却没有增长,为了保证数据的一致性,必须将恢复到扣钱前的状态,这就是回滚。事务与回滚就是为了保证数据的一致性。

  在spring中,使用AOP的技术将事务管理切入到对数据库操做的dao层方法中,就将dao层中的方法用事务管理起来,若是在dao层中方法一旦有异常抛出,事务会自动让数据库进行回滚操做。配置文件参见以下

<?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:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

        <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
                <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
                <property name="jdbcUrl" value="jdbc:mysql:///dbname"></property>
                <property name="user" value="root"></property>
                <property name="password" value="123"></property>
        </bean>

        <!--第一步 配置事务管理-->
        <bean id="transactionMgr" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
                <property name="dataSource" ref="dataSource"></property>
        </bean>
        <!--第二步 配置事务加强,使用AOP技术将事务管理添加到dao层-->
        <tx:advice id="txadvice" transaction-manager="transactionMgr">
                <tx:attributes>
                        <!--name 表达式表示 全部save开头的方法须要事务操做;
                             propagation 表示隔离级别-->
                        <tx:method name="save*" propagation="REQUIRED"/>
                </tx:attributes>
        </tx:advice>
        <!--第三步 配置切面-->
        <aop:config>
                <aop:pointcut id="pointcutdb" expression="execution(* com.blueto.*(..))"/>
                <!--切面-->
                <aop:advisor advice-ref="txadvice" pointcut-ref="pointcutdb"/>
        </aop:config>

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

  --注解方式添加事务管理

  相对于上一种方式,注解方式要简单一些,在配置文件中只须要两步

<?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:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

        <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
                <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
                <property name="jdbcUrl" value="jdbc:mysql:///dbname"></property>
                <property name="user" value="root"></property>
                <property name="password" value="123"></property>
        </bean>

        <!--第一步 配置事务管理-->
        <bean id="transactionMgr" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!--第二步 开户事务注解--> <tx:annotation-driven transaction-manager="transactionMgr"/> 
        <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
                <property name="dataSource" ref="dataSource"></property>
        </bean>
</beans>

  在须要使用事务管理的方法所在类前,添加上注解@Transtional便可。

@Transactional
public class UserDao {
        public void add() {
                System.out.print("在这里添加一个用户");
        }
}
相关文章
相关标签/搜索