Java学习路线-61:MyBatis声明式事务

简介: Java学习路线-61:MyBatis声明式事务

1、完整配置

(1)beans.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
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd
">

    <!-- 配置数据源-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://127.0.0.1:3306/data"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    </bean>

    <!-- 配置 sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="mybatis-config.xml"/>
    </bean>

    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>

    <bean id="StudentDao" class="com.pengshiyu.mybatis.dao.impl.StudentDaoImpl">
        <property name="sqlSession" ref="sqlSessionTemplate"/>
    </bean>

    <!--  声明式事务管理-->
    <!--  配置事务管理器-->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!-- 配置事务通知-->
    <tx:advice id="txAdvice" transaction-manager="txManager">
        <!-- 配置事务的传播特性-->
        <tx:attributes>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>

    <aop:config>
        <aop:pointcut id="pointcut"
        expression="execution(* com.pengshiyu.mybatis.dao.impl.*.* (..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/>
    </aop:config>
</beans>

(2)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>

<settings>
<!-- 打印sql日志 -->
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>

<typeAliases>
<package name="com.pengshiyu.mybatis.entity"/>
</typeAliases>

<mappers>
<mapper resource="StudentMapper.xml"/>
</mappers>

</configuration>

(3)StudentMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd";>

<mapper namespace="com.pengshiyu.mybatis.entity.StudentMapper">
<select id="getById" resultType="Student">
select * from students where id = #{id}
</select>

<select id="selectAll" resultType="Student">
select * from students
</select>

<update id="updateById" parameterType="Student">
update students set age = #{age} where id = #{id}
</update>

<delete id="deleteById" parameterType="Student">
<!-- 故意将sql写错,触发事务管理-->
deletes from students where id = #{id}
</delete>

</mapper>

2、DAO

(1)接口

package com.pengshiyu.mybatis.dao;

import com.pengshiyu.mybatis.entity.Student;

public interface StudentDao {

public void update(Student studentA, int id);
public Student getById(int id);

}

(2)实现

package com.pengshiyu.mybatis.dao.impl;

import com.pengshiyu.mybatis.dao.StudentDao;
import com.pengshiyu.mybatis.entity.Student;
import org.mybatis.spring.SqlSessionTemplate;

public class StudentDaoImpl implements StudentDao {
private SqlSessionTemplate sqlSession;

@Override
public Student getById(int id) {
return sqlSession.selectOne("com.pengshiyu.mybatis.entity.StudentMapper.getById", id);
}

@Override
public void update(Student studentA, int id) {
sqlSession.update("com.pengshiyu.mybatis.entity.StudentMapper.updateById", studentA);
sqlSession.delete("com.pengshiyu.mybatis.entity.StudentMapper.deleteById", id);
}

public void setSqlSession(SqlSessionTemplate sqlSession) {
this.sqlSession = sqlSession;
}
}

3、测试

package com.pengshiyu.mybatis.test;

import com.pengshiyu.mybatis.dao.StudentDao;
import com.pengshiyu.mybatis.entity.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.io.IOException;

public class Demo {
public static void main(String[] args) throws IOException {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

StudentDao studentDao = (StudentDao) context.getBean("StudentDao");

Student studentA = studentDao.getById(1);
studentA.setAge(25);

studentDao.update(studentA, 3);
}
}
            </div>
目录
相关文章
|
3天前
|
存储 关系型数据库 分布式数据库
PostgreSQL 18 发布,快来 PolarDB 尝鲜!
PostgreSQL 18 发布,PolarDB for PostgreSQL 全面兼容。新版本支持异步I/O、UUIDv7、虚拟生成列、逻辑复制增强及OAuth认证,显著提升性能与安全。PolarDB-PG 18 支持存算分离架构,融合海量弹性存储与极致计算性能,搭配丰富插件生态,为企业提供高效、稳定、灵活的云数据库解决方案,助力企业数字化转型如虎添翼!
|
14天前
|
弹性计算 关系型数据库 微服务
基于 Docker 与 Kubernetes(K3s)的微服务:阿里云生产环境扩容实践
在微服务架构中,如何实现“稳定扩容”与“成本可控”是企业面临的核心挑战。本文结合 Python FastAPI 微服务实战,详解如何基于阿里云基础设施,利用 Docker 封装服务、K3s 实现容器编排,构建生产级微服务架构。内容涵盖容器构建、集群部署、自动扩缩容、可观测性等关键环节,适配阿里云资源特性与服务生态,助力企业打造低成本、高可靠、易扩展的微服务解决方案。
1303 5
|
13天前
|
机器学习/深度学习 人工智能 前端开发
通义DeepResearch全面开源!同步分享可落地的高阶Agent构建方法论
通义研究团队开源发布通义 DeepResearch —— 首个在性能上可与 OpenAI DeepResearch 相媲美、并在多项权威基准测试中取得领先表现的全开源 Web Agent。
1330 87
|
2天前
|
弹性计算 安全 数据安全/隐私保护
2025年阿里云域名备案流程(新手图文详细流程)
本文图文详解阿里云账号注册、服务器租赁、域名购买及备案全流程,涵盖企业实名认证、信息模板创建、域名备案提交与管局审核等关键步骤,助您快速完成网站上线前的准备工作。
184 82
2025年阿里云域名备案流程(新手图文详细流程)
|
7天前
|
前端开发
Promise的then方法返回的新Promise对象的状态为“失败(Rejected)”时,链式调用会如何执行?
Promise的then方法返回的新Promise对象的状态为“失败(Rejected)”时,链式调用会如何执行?
242 127