zoukankan      html  css  js  c++  java
  • spring学习之三 数据库操作jdbcTemplate

    概念

      jdbcTemplate就Spring对数据库持久化技术的实现,通过它可以对数据库进行CRUD等操作。

    JDBCTemplate和代码实现

    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 连接池配置

      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语句的,而是在配置文件中配置好连接池。

      从代码的实现步骤来看,可以总结 出连接池的执行步骤:

      第一步 创建连接池的ComboPooledDataSource 对象

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

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

    <?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("在这里添加一个用户");
            }
    }
  • 相关阅读:
    构架设计:负载均衡层设计方案(1)——负载场景和解决方式
    ActiveMQ5.14.1+Zookeeper3.4.9高可用伪分布式部署
    TCP同步与异步,长连接与短连接【转载】
    各种加密解密算法的比较和适用场合(转)
    ElasticSearch安装部署,基本配置(Ubuntu14.04)
    OpenResty--mysql,redis 项目中的应用
    mysql慢日志
    MongoDB之Replica Set(复制集复制)
    pycharm的一些设置和快捷键
    jmap
  • 原文地址:https://www.cnblogs.com/lovemo1314/p/7253207.html
Copyright © 2011-2022 走看看