Spring4


layout: post
title: spring4
subtitle: Spring整合JDBC,Spring的事务
date: 2018-06-15
author: ZL
header-img: img/20180615.jpg
catalog: true
tags:
- spring
- Spring&JDBC
- spring&事务


Spring整合JDBC

简单使用(调用JdbcTemplate方法)

@Test
public void fun1() {
  
  ComboPooledDataSource  dataSource = new ComboPooledDataSource();
  try {
    dataSource.setDriverClass("com.mysql.jdbc.Driver");
    dataSource.setJdbcUrl("jdbc:mysql:///test01");
    dataSource.setUser("root");
    dataSource.setPassword("123456");
  } catch (PropertyVetoException e) {
    e.printStackTrace();
  }
  
  JdbcTemplate jdbcTemplate = new JdbcTemplate();
  jdbcTemplate.setDataSource(dataSource);
  
  
  String sql = "insert into user values(null,'rose') ";
  jdbcTemplate.update(sql);
}

在Spring中使用数据库需要JdbcTemplate对象,这个对象可以对数据库进行各种操作。想要获取JdbcTemplate对象,需要dataSource连接池作为参数。dataSource连接池还保存有关于数据库的数据,

结合applicationContext配置

与数据库匹配的bean类

public class User {

    private Integer id;
    private String name;
    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 interface UserDao {

    //增
    void save(User u);
    //删
    void delete(Integer id);
    //改
    void update(User u);
    //查
    User getById(Integer id);
    //查
    int getTotalCount();
    //查
    List<User> getAll();
    
}

操作数据库的接口类的实现类

在这个类里面增删改查,需要JdbcTemplate的对象才可以


public class UserDaoImpl implements UserDao {

    private JdbcTemplate jt;
    
    public JdbcTemplate getJt() {
        return jt;
    }
    public void setJt(JdbcTemplate jt) {
        this.jt = jt;
    }
    
    @Override
    public void save(User u) {
        String sql = "insert into user values(null,?) ";
        jt.update(sql, u.getName());
    }
    @Override
    public void delete(Integer id) {
        String sql = "delete from user where id = ? ";
        jt.update(sql,id);
    }
    @Override
    public void update(User u) {
        String sql = "update  user set name = ? where id=? ";
        jt.update(sql, u.getName(),u.getId());
    }
    @Override
    public User getById(Integer id) {
        String sql = "select * from user where id = ? ";
        return jt.queryForObject(sql,new RowMapper<User>(){
            @Override
            public User mapRow(ResultSet rs, int arg1) throws SQLException {
                User u = new User();
                u.setId(rs.getInt("id"));
                u.setName(rs.getString("name"));
                return u;
            }}, id);
        
    }
    @Override
    public int getTotalCount() {
        String sql = "select count(*) from user  ";
        Integer count = jt.queryForObject(sql, Integer.class);
        return count;
    }

    @Override
    public List<User> getAll() {
        String sql = "select * from user  ";
        List<User> list = jt.query(sql, new RowMapper<User>(){
            @Override
            public User mapRow(ResultSet rs, int arg1) throws SQLException {
                User u = new User();
                u.setId(rs.getInt("id"));
                u.setName(rs.getString("name"));
                return u;
            }});
        return list;
    }

}

applicationContext配置

  <?xml version="1.0" encoding="UTF-8"?>
  <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd ">

  <!-- 1.将连接池放入spring容器 -->
  <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" >
    <property name="jdbcUrl" value="jdbc:mysql:///test01" ></property>
    <property name="driverClass" value="com.mysql.jdbc.Driver" ></property>
    <property name="user" value="root" ></property>
    <property name="password" value="123456" ></property>
  </bean>

  <!-- 2.将JDBCTemplate放入spring容器 -->
  <bean name="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" >
    <property name="dataSource" ref="dataSource" ></property>
  </bean>

  <!-- 3.将UserDao放入spring容器 -->
  <bean name="userDao" class="zl.jdbc.UserDaoImpl" >
    <property name="jt" ref="jdbcTemplate" ></property>
  </bean>
    
  </beans>


  <!--
  在用注解获取到userDao对象时,jdbcTemplate对象会被创建并set到userDao中,创建jdbcTemplate对象时,dataSource对象会被创建并set到jdbcTemplate中去。

  userDao <--- jdbcTemplate <--- dataSource
  -->

调用

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Demo {

    @Resource(name="userDao")
    private UserDao ud;
    
    @Test
    public void fun2() {
        User u = new User();
        u.setName("tom");
        ud.save(u);
    }
}

扩展1 JdbcDaoSupport

从JdbcDaoSupport可以获取到JdbcTemplate对象

上面的代码修改UserDaoImpl

public class UserDaoImpl extends JdbcDaoSupport implements UserDao {
    @Override
    public void save(User u) {
        String sql = "insert into user values(null,?) ";
        super.getJdbcTemplate().update(sql, u.getName());
    }
    @Override
    public void delete(Integer id) {
        String sql = "delete from user where id = ? ";
        super.getJdbcTemplate().update(sql,id);
    }
    @Override
    public void update(User u) {
        String sql = "update  user set name = ? where id=? ";
        super.getJdbcTemplate().update(sql, u.getName(),u.getId());
    }
    @Override
    public User getById(Integer id) {
        String sql = "select * from user where id = ? ";
        return super.getJdbcTemplate().queryForObject(sql,new RowMapper<User>(){
            @Override
            public User mapRow(ResultSet rs, int arg1) throws SQLException {
                User u = new User();
                u.setId(rs.getInt("id"));
                u.setName(rs.getString("name"));
                return u;
            }}, id);
        
    }
    @Override
    public int getTotalCount() {
        String sql = "select count(*) from user  ";
        Integer count = super.getJdbcTemplate().queryForObject(sql, Integer.class);
        return count;
    }

    @Override
    public List<User> getAll() {
        String sql = "select * from user  ";
        List<User> list = super.getJdbcTemplate().query(sql, new RowMapper<User>(){
            @Override
            public User mapRow(ResultSet rs, int arg1) throws SQLException {
                User u = new User();
                u.setId(rs.getInt("id"));
                u.setName(rs.getString("name"));
                return u;
            }});
        return list;
    }
}

修改applicationContext

删除JDBCTemplate配置,userDao的参数改为dataSource

  <!-- 1.将连接池放入spring容器 -->
  <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" >
    <property name="jdbcUrl" value="jdbc:mysql:///test01" ></property>
    <property name="driverClass" value="com.mysql.jdbc.Driver" ></property>
    <property name="user" value="root" ></property>
    <property name="password" value="123456" ></property>
  </bean>

  <!-- 3.将UserDao放入spring容器 -->
  <bean name="userDao" class="cn.itcast.a_jdbctemplate.UserDaoImpl" >
    <!-- <property name="jt" ref="jdbcTemplate" ></property> -->
    <property name="dataSource" ref="dataSource" ></property>
  </bean>

扩展2 properties配置文件

把数据库的配置信息放在外面

创建db.properties

//加一个前缀jdbc.可以避免冲突
jdbc.jdbcUrl=jdbc:mysql:///hibernate_32
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=1234

applicationContext使用

  <!-- 指定spring读取db.properties配置 -->
  <context:property-placeholder location="classpath:db.properties"  />

  <!-- 1.将连接池放入spring容器 -->
  <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" >
    <property name="jdbcUrl" value="${jdbc.jdbcUrl}" ></property>
    <property name="driverClass" value="${jdbc.driverClass}" ></property>
    <property name="user" value="${jdbc.user}" ></property>
    <property name="password" value="${jdbc.password}" ></property>
  </bean>

Spring中的aop事务

Spring封装了事务管理代码

编码式(不使用)

applicationContext配置

  (部分代码)
  <!-- 事务核心管理器,封装了所有事务操作. 依赖于连接池 -->
  <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" >
    <property name="dataSource" ref="dataSource" ></property>
  </bean>
  <!-- 事务模板对象 -->
  <bean name="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate" >
    <property name="transactionManager" ref="transactionManager" ></property>
  </bean>

  <!-- 1.将连接池 -->
  <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" >
    <property name="jdbcUrl" value="${jdbc.jdbcUrl}" ></property>
    <property name="driverClass" value="${jdbc.driverClass}" ></property>
    <property name="user" value="${jdbc.user}" ></property>
    <property name="password" value="${jdbc.password}" ></property>
  </bean>

  <!-- 2.Dao-->
  <bean name="accountDao" class="cn.itcast.dao.AccountDaoImpl" >
    <property name="dataSource" ref="dataSource" ></property>
  </bean>
  <!-- 3.Service-->
  <bean name="accountService" class="cn.itcast.service.AccountServiceImpl" >
    <property name="ad" ref="accountDao" ></property>
    <property name="tt" ref="transactionTemplate" ></property>
  </bean>  

事务调用

tt.execute(new transactionCallbackWithoutResult(){
  protected void doInTransactionWithoutResult(TransactionStatus status){
    //这里进行数据的操作
    xxxDao.增删改查
    
    //这里的代码都是在事务中执行的
  }
});

xml配置实现事务

applicationContext配置

  <!-- 配置事务通知 -->
  <tx:advice id="txAdvice" transaction-manager="transactionManager" >
    <tx:attributes>
        <!-- 以方法为单位,指定方法应用什么事务属性
            isolation:隔离级别
            propagation:传播行为
            read-only:是否只读
         -->
        <tx:method name="save*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
        <tx:method name="persist*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
        <tx:method name="update*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
        <tx:method name="modify*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
        <tx:method name="delete*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
        <tx:method name="remove*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
        <tx:method name="get*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true" />
        <tx:method name="find*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true" />
        <tx:method name="transfer" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
    </tx:attributes>
  </tx:advice>


  <!-- 配置织入 -->
  <aop:config  >
    <!-- 配置切点表达式 -->
    <aop:pointcut expression="execution(* cn.itcast.service.*ServiceImpl.*(..))" id="txPc"/>
    <!-- 配置切面 : 通知+切点
            advice-ref:通知的名称
            pointcut-ref:切点的名称
     -->
    <aop:advisor advice-ref="txAdvice" pointcut-ref="txPc" />
  </aop:config>

调用

@Override
@Transactional(isolation=Isolation.REPEATABLE_READ,propagation=Propagation.REQUIRED,readOnly=false)
public void transfer(final Integer from,final Integer to,final Double money) {
      //减钱
      ad.decreaseMoney(from, money);
      int i = 1/0;
      //加钱
      ad.increaseMoney(to, money);
}

注解配置

applicationContext配置

  <?xml version="1.0" encoding="UTF-8"?>
  <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd ">

  <!-- 指定spring读取db.properties配置 -->
  <context:property-placeholder location="classpath:db.properties"  />

  <!-- 事务核心管理器,封装了所有事务操作. 依赖于连接池 -->
  <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" >
    <property name="dataSource" ref="dataSource" ></property>
  </bean>
  <!-- 事务模板对象 -->
  <bean name="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate" >
    <property name="transactionManager" ref="transactionManager" ></property>
  </bean>

  <!-- 开启使用注解管理aop事务 -->
  <tx:annotation-driven/>

  <!-- 1.将连接池 -->
  <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" >
    <property name="jdbcUrl" value="${jdbc.jdbcUrl}" ></property>
    <property name="driverClass" value="${jdbc.driverClass}" ></property>
    <property name="user" value="${jdbc.user}" ></property>
    <property name="password" value="${jdbc.password}" ></property>
  </bean>



  <!-- 2.Dao-->
  <bean name="accountDao" class="cn.itcast.dao.AccountDaoImpl" >
    <property name="dataSource" ref="dataSource" ></property>
  </bean>
  <!-- 3.Service-->
  <bean name="accountService" class="cn.itcast.service.AccountServiceImpl" >
    <property name="ad" ref="accountDao" ></property>
    <property name="tt" ref="transactionTemplate" ></property>
  </bean>  

  </beans>

调用

@Override
@Transactional(isolation=Isolation.REPEATABLE_READ,propagation=Propagation.REQUIRED,readOnly=false)
public void transfer(final Integer from,final Integer to,final Double money) {
      //减钱
      ad.decreaseMoney(from, money);
      int i = 1/0;
      //加钱
      ad.increaseMoney(to, money);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
疫情居家办公系统管理系统按照操作主体分为管理员和用户。管理员的功能包括办公设备管理、部门信息管理、字典管理、公告信息管理、请假信息管理、签到信息管理、留言管理、外出报备管理、薪资管理、用户管理、公司资料管理、管理员管理。用户的功能等。该系统采用了MySQL数据库,Java语言,Spring Boot框架等技术进行编程实现。 疫情居家办公系统管理系统可以提高疫情居家办公系统信息管理问题的解决效率,优化疫情居家办公系统信息处理流程,保证疫情居家办公系统信息数据的安全,它是一个非常可靠,非常安全的应用程序。 管理员权限操作的功能包括管理公告,管理疫情居家办公系统信息,包括外出报备管理,培训管理,签到管理,薪资管理等,可以管理公告。 外出报备管理界面,管理员在外出报备管理界面中可以对界面中显示,可以对外出报备信息的外出报备状态进行查看,可以添加新的外出报备信息等。签到管理界面,管理员在签到管理界面中查看签到种类信息,签到描述信息,新增签到信息等。公告管理界面,管理员在公告管理界面中新增公告,可以删除公告。公告类型管理界面,管理员在公告类型管理界面查看公告的工作状态,可以对公告的数据进行导出,可以添加新公告的信息,可以编辑公告信息,删除公告信息
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值