Spring整合JDBC与Spring管理事务

补充上一篇未发的东西

使用注解的方式配置aop

1.     开始注解模式

<aop:aspectj-autoproxy></aop:aspectj-autoproxy>

2.     注解切面

再通知上面加上一个注解@Aspect

@Aspect

public class MyAdvice


再通知的方法上面加上切点

五种

@Before(表达式)@AfterReturning @Around
@After @AfterThrowing

@Before("MyAdvice.pc()")

    publicvoid before(){

        System.out.println("在目标对象方法前调用");

}

书写表达式有两种

1.     直接写

@ Before ("execution(*cn.hd.springProxyAnnotation.impl.*ServiceImpl.*(..))")

  public voidbefore(){

       System.out.println("在目标对象方法前调用");

    }

2.     配置一个切点 调用该类的方法获得切点

@Pointcut("execution(* cn.hd.springProxyAnnotation.impl.*ServiceImpl.*(..))")

    publicvoid pc(){

    }

  @Before("MyAdvice.pc()")

    publicvoid before(){

       System.out.println("在目标对象方法前调用");

Spring整合JDBC(手动创建对象)

Spring是一个容器

Spring有一个JAR包提供了一个叫做JDBCTemplate模板所以他能对数据库操作。

Spring还提供了很多模板 针对hebernate,Mybatis模板。JDBCemplate跟Dbutols中的QueryRunner极度相似

整合JDBC

1.     导包

2.     c3p0,JDBC驱动包 Spring-jdbc spring-tx


3     使用一个JdbcTemplate模板对数据库进行操作,需要数据库连接

给他连接两种方式  1.Connection  2.dataSource

public void  fun() throwsPropertyVetoException {

       ComboPooledDataSource dataSource = new ComboPooledDataSource();

       dataSource.setDriverClass("com.mysql.jdbc.Driver");

       dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/springjdbc");

       dataSource.setUser("root");

       dataSource.setPassword("123");

       JdbcTemplate jdbcTemplate = new JdbcTemplate();

       jdbcTemplate.setDataSource(dataSource);

       String sql="INSERT  INTOt_user(uname,ubalance) VALUES ('白学光',12138)";

       jdbcTemplate.update(sql);

Spring管理对象的方式

UserDao接口 UserDaoImpl实现类 applicationContext.xml


使用spring管理对象开发,一定要搞清楚对象之间的依赖关系。

将对应的bean类配置到配置文件当中 将属性的注入写好

<bean name="dataSource"class="com.mchange.v2.c3p0.ComboPooledDataSource">

               <property name="driverClass"value="com.mysql.jdbc.Driver"></property>

               <property name="jdbcUrl"value="jdbc:mysql://localhost:3306/springjdbc"></property>

               <property name="user"value="root"></property>

               <property name="password"value="123"></property>

       </bean>

        <beanname="jdbcTemplate"class="org.springframework.jdbc.core.JdbcTemplate">

               <property name="dataSource"ref="dataSource"></property>

       </bean>

       <bean name="userDao"class="cn.hd.SpringJDBC.Impl.UserDaoImpl">

               <property name="jdbcTemplate"ref="jdbcTemplate"></property>

       </bean>

JdbcTemplateApi

增删改:调用Jdbctemplate update方法 如果有参数直接按顺序写在方法后面即可

jdbcTemplate.update(sql, user.getUname(),user.getUbalance());

查询:调用jdbctemplate query方法 参数同上。结果集的处理,要传一个RewMapper内名内部类

List<User> list = jdbcTemplate.query(sql, newRowMapper<User>

               () {

           @Nullable

           @Override

           public User mapRow(ResultSet resultSet, int i) throws SQLException {

               User user = new User();

                user.setUname(resultSet.getString("uname"));

               user.setUbalance(resultSet.getInt("ubalance"));

               user.setUid(resultSet.getInt("uid"));

               return user;

            }

        });

       return list;

spring提供了一个父类JdbcDaoSupport这个父类中,提供了jdbcTemplate模板

在实现dao类时可以直接使用。并且在配置bean时,依赖关系改变,dao类时直接依赖于

dataSource

   Spring读取配置文件

db,properties 书写配置文件要注意  健名要加前缀,避免和关键字重复

如何读取配置文件在applicationContext.xml中加上一条配置

<context:property-placeholderlocation="classpath:cn/hd/SpringJDBC/db.properties"></context:property-placeholder>

location是配置文件的地址

获得配置文件的地址

<property name="driverClass"value="${jdbc.driverClass}"></property>

Spring管理事务

PlatformTransactionManager  帮助我们管理任意平台的事务

Jdbc  DataSourceTransactionManger

hibernate hibernateTransactionManager

…    …TransactionManager

事务:四大特性(在前几篇文章已经发过在这里不多做解释)

(1)     一致性 (2)原子性(3)持久性 (4)隔离性

事务安全:

事务线程安全:脏读   不可重复读 幻读  读未提交

隔离级别:   1  2  4(读已提交)  8

所有事务的操作有三步:

开启事务

提交事务

回滚事务

Spring管理事务 利用的是spring aop思维 将事务的操作织入到目标对象中

Spring管理 事务的属性

隔离级别  是否只读  事务的传播行为(7种)


Spring管理事务的方式:

(1)     代码式

1.     配置事务管理对象

2.     配置事务管理的模板

3.     在service中注入模板对象 然后调用模板对象的execute

@Resource(name = "transactionTemplate")

    privateTransactionTemplate tt;

    @Override

    publicvoid transform(Integer form, Integer to, Integer money) {

     tt.execute(new TransactionCallbackWithoutResult() {

         @Override

         protected void doInTransactionWithoutResult(TransactionStatustransactionStatus) {

             userDao.increase(to,money);

             userDao.decrease(form,money);

          }

      });

(2)     xml配置

1.     事务管理的对象

<!--配置事务管理对象-->

     <beanname="transactionManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

        <property name="dataSource"ref="dataSouse"></property>

    </bean>

2.     事务的通知

标签名 tx:advice     id给当前的事务起个标记  tran…配置刚刚的事务管理对象

配置参数:method  name 可以是具体某个方法(方法名)比较麻烦

可以使用通配符的方法去配置

add*  delate* update*get*

find*  persist* remove*modify*

要求的你service的命名必须规范

Isolation 隔离级别使用默认即可 4级别 Default

Propagation事务的传播行为 required

read-only是否只读  如果查找 true  否则为false

<!--配置通知-->

    <tx:advice id="myAdvice"transaction-manager="transactionManager">

       <tx:attributes>

           <tx:method name="transform" isolation="DEFAULT"propagation="REQUIRED" read-only="false"/>

           <tx:method name="get*" isolation="DEFAULT" propagation="REQUIRED"read-only="true"/>

           <tx:method name="add*" isolation="DEFAULT"propagation="REQUIRED" read-only="false"/>

           <tx:method name="update*" isolation="DEFAULT"propagation="REQUIRED" read-only="false"/>

           <tx:method name="delete*" isolation="DEFAULT"propagation="REQUIRED" read-only="false"/>

           <tx:method name="find*" isolation="DEFAULT"propagation="REQUIRED" read-only="true"/>

           <tx:method name="persist*" isolation="DEFAULT"propagation="REQUIRED" read-only="false"/>

           <tx:method name="modify*" isolation="DEFAULT"propagation="REQUIRED" read-only="false"/>

           <tx:method name="remove*" isolation="DEFAULT"propagation="REQUIRED" read-only="false"/>

       </tx:attributes>

</tx:advice>

3.     将通知织入到目标对象   注意配置切面不再使用aop:aspect而是advisor

<!--将通知织入到目标对象-->

   <aop:config>

       <aop:pointcut id="txPc" expression="execution(*cn.hd.springTransaction.Impl.*ServiceImpl.*(..))"></aop:pointcut>

       <aop:advisor advice-ref="myAdvice" pointcut-ref="txPc"></aop:advisor>

   </aop:config>

(3)     注解配置

1.     事务管理对象

2.     注解

<!--开启注解模式-->

<tx:annotation-driven></tx:annotation-driven>

3.     在想要设置事务的地方加上注解

@Transactional(isolation =Isolation.DEFAULT,propagation = Propagation.REQUIRED,readOnly = false)

这个注解有两个位置

1.在类上面 该类中所有的方法都会使用以上参数的事务

2.方法名上面 该方法使用参数中的事务如果两个都设置以方法名上面的事务为准












猜你喜欢

转载自blog.csdn.net/leizhenjiang/article/details/80932054