基于aop/tx命名空间的配置

Student域

package com.smart.domain;

public class Student {
    private int studentId;
    private String stuName;
    private String sex;
    private int age;
    private String phone;

    public int getStudentId() {
        return studentId;
    }

    public void setStudentId(int studentId) {
        this.studentId = studentId;
    }

    public String getStuName() {
        return stuName;
    }

    public void setStuName(String stuName) {
        this.stuName = stuName;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    @Override
    public String toString() {
        return "Student{" +
                "studentId=" + studentId +
                ", stuName='" + stuName + '\'' +
                ", sex='" + sex + '\'' +
                ", age=" + age +
                ", phone='" + phone + '\'' +
                '}';
    }
}

StudentDAO层


@Repository
public class StudentDao {
    private JdbcTemplate jdbcTemplate;

    public void addStudent(final Student student){
        final String sql="insert into t_stu(name,sex,age,phone) values(?,?,?,?)";
        KeyHolder keyHolder = new GeneratedKeyHolder();
        jdbcTemplate.update(new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
                PreparedStatement ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
                ps.setString(1,student.getStuName());
                ps.setString(2,student.getSex());
                ps.setInt(3,student.getAge());
                ps.setString(4,student.getPhone());
                return ps;
            }
        },keyHolder);
        student.setStudentId(keyHolder.getKey().intValue());
    }

    public void addSudentAgain(final Student student){
       Object[] params=new Object[]{student.getStuName(),student.getSex(),student.getAge(),student.getPhone()};
        final String sql="insert into t_stu(name,sex,age,phone) values(?,?,?,?)";
        jdbcTemplate.update(sql,params);
    }

    public Student getStudent(final int stuId){
        String sql="select name,sex,age,phone from t_stu where stu_id=?";
        final Student student=new Student();
        jdbcTemplate.query(sql, new Object[]{stuId}, new RowCallbackHandler() {
            @Override
            public void processRow(ResultSet rs) throws SQLException {
                student.setStudentId(stuId);
                student.setStuName(rs.getString("name"));
                student.setSex(rs.getString("sex"));
                student.setAge(rs.getInt("age"));
                student.setPhone(rs.getString("phone"));
            }
        });
        return student;
    }

    @Autowired
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
}

StudentService

package com.smart.service;

@Service
public class StudentService {
    private StudentDao studentDao;

    public void addStudent(Student student){
        studentDao.addStudent(student);
    }

    public void addStudentAgain(Student student){
        studentDao.addSudentAgain(student);
    }

    public Student getStudent(final int stuId){
        Student student = studentDao.getStudent(stuId);
        return student;
    }

    @Autowired
    public void setStudentDao(StudentDao studentDao) {
        this.studentDao = studentDao;
    }
}

applicationContext-tx.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:context="http://www.springframework.org/schema/context"
       xmlns:p="http://www.springframework.org/schema/p" 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.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
    <context:component-scan base-package="com.smart"/>

    <context:property-placeholder location="classpath:jdbc.properties"/>

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
          destroy-method="close"
          p:driverClassName="${jdbc.driverClassName}"
          p:url="${jdbc.url}"
          p:username="${jdbc.username}"
          p:password="${jdbc.password}"/>

    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"
          p:dataSource-ref="dataSource"/>
    <aop:config>
        <aop:pointcut id="serviceMethod" expression="execution(* com.smart.service.*Student.*(..))"/>
        <aop:advisor pointcut-ref="serviceMethod" advice-ref="txAdvice"/>
    </aop:config>

    <!--基于数据源的数据管理器-->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
          p:dataSource-ref="dataSource"/>

    <tx:advice id="txAdvice" transaction-manager="txManager">
        <tx:attributes>
            <tx:method name="get*" read-only="false"/>
            <tx:method name="add*" rollback-for="Exception"/>
            <tx:method name="update*"/>
        </tx:attributes>
    </tx:advice>
</beans>

测试类

package com.smart;

import com.smart.domain.Student;
import com.smart.service.StudentService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTransactionalTestNGSpringContextTests;

@RunWith(JUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext-tx.xml"})
public class TestStudentServiceAgain extends AbstractTransactionalTestNGSpringContextTests{
    @Autowired
    private StudentService studentService;

    @Test
    public void testAddStudent(){
        Student student = new Student();
        student.setStuName("xiaowang");
        student.setSex("女");
        student.setAge(8);
        student.setPhone("186995");
        studentService.addStudent(student);
    }

}
posted on 2018-12-04 21:13  溪水静幽  阅读(780)  评论(0)    收藏  举报