149_Java_SpringMybatis整合_AOP事物

举报
alexsully 发表于 2021/08/28 22:12:03 2021/08/28
【摘要】 Spring&Mybatis整合 AOP事物case

MyBatis-Spring 需要以下版本

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.alex.Spring</groupId>
    <artifactId>Spring_Mybatis</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>mybatis_spring</module>
        <module>Mybatis-review</module>
    </modules>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>
        <!--Spring操作数据库的话,还需要一个spring-jdbc-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.13</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.2</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.10</version>
        </dependency>
    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

</project>

要和Spring一起使用MyBatis,需要在Spring应用上下文中定义至少两样东西:
1 SqlSessionFactory(SqlSessionFactoryBean来创建SqlSessionFactory[需要一个DataSource])
2 一个数据映射器类

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

    <import resource="spring-mybatis.xml"/>
    
</beans>

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

    <!--DataSource:使用Spring的数据源替换Mybatis的配置  c3p0  dbcp  druid
    这里使用Spring提供的JDBC : org.springframework.jdbc.datasource
    -->

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/test?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    </bean>


    <!--sqlSessionFactory 内部可以配置 接管 mybatis相关属性  -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!--绑定Mabatis配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <property name="mapperLocations" value="classpath*:com/alex/mapper/*.xml"/>
    </bean>


    <!--SqlSessionTemplate:就是我们使用的sqlSession-->

    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <!--只能使用构造器注入sqlSessionFactory,因为它没有set方法-->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>


    <bean id="userMapper" class="com.alex.mapper.UserMapperImpl">
        <property name="sqlSession" ref="sqlSession"/>
    </bean>

    <bean id="userMapper2" class="com.alex.mapper.UserMapperImpl2">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>


    <!-- 事物相关 利用AOP思想 -->
    <!--1 配置声明式事务-->

    <bean id="transactionManage" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!--2 结合AOP实现事务的织入-->
    <!--配置事务通知-->

    <tx:advice id="txAdvice" transaction-manager="transactionManage">
        <!--给那些方法配置事务-->
        <!--配置事务的传播特性:new propagation= -->
        <tx:attributes>
            <tx:method name="add" propagation="REQUIRED"/>
            <tx:method name="delete" propagation="REQUIRED"/>
            <tx:method name="update" propagation="REQUIRED"/>
            <tx:method name="query" read-only="true"/>
            <tx:method name="*"  propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>

    <!--3 配置事务切入-->
    <!-- execution()表达式的主体 第一个*符号 表示返回值的类型任意 -->
    <!--aop 切面 aspect 就是个类, advice通知-类中方法,pointcut 切入点-->
    <!--切入点  expression:表达式匹配要执行的方法-->
    <!--执行环绕; advice-ref执行方法  pointcut-ref切入点-->

    <aop:config>
        <aop:pointcut id="txPointCut" expression="execution(* com.alex.mapper.*.*(..))" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    </aop:config>

    <!-- TransactionImpl 不需要属性,但是它继承了SqlSessionDaoSupport(属性SqlSessionTemplate 依赖一个SqlSessionFactory)-->

    <bean id="transaction" class="com.alex.mapper.TransactionImpl">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>

</beans>

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--configuration核心配置文件-->
<configuration>
    <typeAliases>
        <package name="com.alex.pojo"/>
    </typeAliases>

    <!--设置-->
    <!--<settings>-->
    <!--<setting name="" value=""/>-->
    <!--</settings> -->

<!--    <environments default="development">-->
<!--        <environment id="development">-->
<!--            <transactionManager type="JDBC"></transactionManager>-->
<!--            <dataSource type="POOLED">-->
<!--                <property name="driver" value="com.mysql.jdbc.Driver"/>-->
<!--                <property name="url" value="jdbc:mysql://localhost:3306/test?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>-->
<!--                <property name="username" value="root"/>-->
<!--                <property name="password" value="123456"/>-->
<!--            </dataSource>-->
<!--        </environment>-->
<!--    </environments>-->


<!--    <mappers>-->
<!--        <mapper resource="com/alex/mapper/UserMapper.xml"/>-->
<!--    </mappers>-->

</configuration>

pojo_User

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private int id;
    private String name;
    private String password;
    private String address;
    private String phone;

    public User(String name, String password, String address, String phone) {
        this.name = name;
        this.password = password;
        this.address = address;
        this.phone = phone;
    }
}

mapper_UserMapper_UserMapperImp1&2

public interface UserMapper {
    public List<User> selectUser();
}


public class UserMapperImpl implements UserMapper {

    private SqlSessionTemplate sqlSession;

    public void setSqlSession(SqlSessionTemplate sqlSession) {
        this.sqlSession = sqlSession;
    }
    public List<User> selectUser() {
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        return mapper.selectUser();
    }
}

public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper {
    
    public List<User> selectUser() {
        return getSqlSession().getMapper(UserMapper.class).selectUser();
    }
}

mapper_UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--configuration核心配置文件-->
<mapper namespace="com.alex.mapper.UserMapper">
    <select id="selectUser" resultType="com.alex.pojo.User">
        select * from user;
    </select>
</mapper>

mapper_Transaction_TransactionImpl

public interface Transaction {
    public List<User> selectUser();
    //添加一个用户
    public int addUser(User user);

    //删除一个用户
    public int deleteUser(int id);

}


public class TransactionImpl extends SqlSessionDaoSupport implements Transaction {
    public List<User> selectUser() {
        Transaction mapper = getSqlSession().getMapper(Transaction.class);
        User user1 = new User("alex", "111", "chengdu", "135333");
        addUser(user1);
        deleteUser(1);
        return mapper.selectUser();
    }

    public int addUser(User user) {
        return getSqlSession().getMapper(Transaction.class).addUser(user);
    }

    public int deleteUser(int id) {
        return getSqlSession().getMapper(Transaction.class).deleteUser(id);
    }
}

mapper_Transaction.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--configuration核心配置文件-->
<mapper namespace="com.alex.mapper.Transaction">

    <select id="selectUser" resultType="com.alex.pojo.User">
        select * from user;
    </select>

    <insert id="addUser" parameterType="user">
        insert into user (name ,password, address, phone) value (#{name}, #{password},#{address},#{phone})
    </insert>

    <delete id="deleteUser" parameterType="int">
        delete  from user where  id = #{id}
    </delete>

</mapper>

测试

public class UserMapperImplTest {

    @Test
    public void selectUser() {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserMapper userMapper = context.getBean("userMapper", UserMapper.class);

        List<User> users = userMapper.selectUser();
        for (User user : users) {
            System.out.println(user);
        }
    }

    @Test
    public void  test3() throws IOException {

        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserMapper userMapper = context.getBean("userMapper2", UserMapper.class);
        List<User> users = userMapper.selectUser();
        for (User user : users) {
            System.out.println(user);
        }

    }


    @Test
    public void  test4() throws IOException {

        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        Transaction transaction = context.getBean("transaction", Transaction.class);
        List<User> users = transaction.selectUser();

        for (User user : users) {
            System.out.println(user);
        }

    }


    @Test
    public void  test2() throws IOException {

        String resource = "mybatis-config.xml";
        InputStream is  = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        System.out.println(sqlSession);

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> users = mapper.selectUser();
        for (User user : users) {
            System.out.println(user);
        }
    }

}

【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。