一、业务代码
1.1、pom
<dependencies><!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.26</version></dependency><!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc --><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>5.3.27</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.11</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>2.1.0</version></dependency><dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper</artifactId><version>5.3.2</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-beans</artifactId><version>5.2.5.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.2.5.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-core</artifactId><version>5.2.5.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-expression</artifactId><version>5.2.5.RELEASE</version></dependency><dependency><groupId>commons-logging</groupId><artifactId>commons-logging</artifactId><version>1.1.1</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.2.16</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.13.2</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.76</version></dependency><!-- 普通maven项目中使用Sl4j注解 --><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.22</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-api</artifactId><version>1.7.32</version></dependency><dependency><groupId>ch.qos.logback</groupId><artifactId>logback-classic</artifactId><version>1.2.10</version></dependency></dependencies>
1.2、实体
1.2.1、UserDO
package org.star.entity.model;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;import java.io.Serializable;/*** @Author:* @Date: 2023/8/28 16:51* @Description:*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserDO implements Serializable {/*** 编号*/private Integer id;/*** 用户名*/private String username;/*** 密码*/private String password;/*** 手机号码*/private String mobile;/*** 用户状态(0启用、1禁用)*/private Integer status;
}
1.2.2、RoleUserDO
package org.star.entity.model;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;import java.io.Serializable;/*** @Author : 一叶浮萍归大海* @Date: 2023/8/28 21:38* @Description:*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class RoleUserDO implements Serializable {/*** 用户ID*/private Integer uId;/*** 角色ID*/private Integer rId;/*** 删除标识(0未删除、1已删除)*/private Integer deleted;
}
1.3、mapper
1.3.1、UserMapper.xml
package org.star.mapper;import org.star.entity.model.UserDO;import java.util.List;/*** @Author:* @Date: 2023/8/28 16:53* @Description:*/
public interface UserMapper {/*** 查询所有用户信息* @return*/List<UserDO> listAllUser();/*** 根据ID查询用户* @param id 用户ID* @return*/UserDO getUserById(Long id);/*** 禁用用户* @param id 用户ID* @return*/boolean disableUser(Integer id);}
1.3.2、RoleUserMapper.xml
package org.star.mapper;/*** @Author : 一叶浮萍归大海* @Date: 2023/8/28 21:45* @Description:*/
public interface RoleUserMapper {/*** 根据用户ID删除角色* @param uId* @return*/boolean delUserRole(Integer uId);}
1.4、UserService
package org.star.service;import com.github.pagehelper.PageInfo;
import org.star.entity.model.UserDO;import java.util.List;/*** @Author: 一叶浮萍归大海* @Date: 2023/8/28 17:41* @Description:*/
public interface UserService {/*** 查询所有用户信息** @return*/List<UserDO> listAllUser();/*** 分页查询用户信息* @param pageNum 当前页码* @param pageSize 每页显示的记录数* @return*/PageInfo<UserDO> pageUser(int pageNum, int pageSize);/*** 禁用用户* @param uId 用户ID* @return*/boolean disableUser(Integer uId);
}
1.5、UserServiceImpl
package org.star.service.impl;import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.star.entity.model.UserDO;
import org.star.mapper.RoleUserMapper;
import org.star.mapper.UserMapper;
import org.star.service.UserService;import javax.annotation.Resource;
import java.util.List;/*** @Author: 一叶浮萍归大海* @Date: 2023/8/28 17:41* @Description:*/
@Service
public class UserServiceImpl implements UserService {@Resourceprivate UserMapper userMapper;@Resourceprivate RoleUserMapper roleUserMapper;@Resourceprivate DataSourceTransactionManager transactionManager;@Overridepublic List<UserDO> listAllUser() {return userMapper.listAllUser();}@Overridepublic PageInfo<UserDO> pageUser(int pageNum, int pageSize) {// 设置当前页码以及每页显示的记录数PageHelper.startPage(pageNum,pageSize);// 执行查询List<UserDO> userDOS = userMapper.listAllUser();// 设置pageInfo对象PageInfo<UserDO> pageInfo = new PageInfo<>(userDOS);return pageInfo;}/*** 正常情况下,事务全部提交* @param uId 用户ID* @return*/@Overridepublic boolean disableUser(Integer uId) {TransactionDefinition td = new DefaultTransactionDefinition();TransactionStatus transactionStatus = transactionManager.getTransaction(td);try {// 1、禁用当前用户boolean disableResult = userMapper.disableUser(uId);// 两个操作之前模拟异常,看事务是否会回滚int i = 10 /0;// 2、删除用户关联的角色信息boolean delResult = roleUserMapper.delUserRole(uId);// 提交事务transactionManager.commit(transactionStatus);if (disableResult && delResult) {return true;}} catch (Exception e) {// 回滚事务transactionManager.rollback(transactionStatus);}return false;}
}
二、配置信息
2.1、jdbc.properties
db.driverClass=com.mysql.cj.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/20230828_spring5?useSSL=false&useUnicode=true&characterEncoding=UTF8&serverTimezone=GMT
db.username=root
db.password=123456
2.2、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:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"><!--组件扫描--><context:component-scan base-package="org.star"></context:component-scan><context:property-placeholder location="jdbc.properties"></context:property-placeholder><bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"><property name="driverClassName" value="${db.driverClass}"></property><property name="url" value="${db.url}"></property><property name="username" value="${db.username}"></property><property name="password" value="${db.password}"></property></bean><!--配置sqlSessionFactory,注入相关属性--><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><property name="dataSource" ref="dataSource"></property><property name="typeAliasesPackage" value="org.star.entity.model"></property><property name="mapperLocations" value="classpath:mapper/*.xml"></property><property name="configuration"><bean class="org.apache.ibatis.session.Configuration"><property name="logImpl" value="org.apache.ibatis.logging.stdout.StdOutImpl"></property></bean></property><property name="plugins"><array><bean class="com.github.pagehelper.PageInterceptor"><property name="properties"><!--reasonable=true解释:如果用户输入的不合理的pageSize参数,pageHelper会自动进行调整--><value>helperDialect=mysqlreasonable=true</value></property></bean></array></property></bean><!--配置mapper的位置,并指定sqlSessionFactorysqlSession = sqlSessionFactory.openSession();mapper = sqlSession.getMapper();--><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="basePackage" value="org.star.mapper"></property><property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property></bean><!--配置事务管理器--><bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource"></property></bean>
</beans>
三、测试
3.1、AppTest
package org.star;import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.star.entity.model.UserDO;
import org.star.mapper.UserMapper;
import org.star.service.UserService;
import org.star.service.impl.UserServiceImpl;import java.util.List;/*** Unit test for simple App.*/
@Slf4j
public class AppTest {private ClassPathXmlApplicationContext context = null;@Beforepublic void initApplicationContext() {context = new ClassPathXmlApplicationContext("applicationContext.xml");}// ================================= service test ================================@Testpublic void txTest() {UserService userService = context.getBean(UserServiceImpl.class);boolean result = userService.disableUser(1);log.info("result:{}", result);}@Testpublic void pageUserTest() {UserService userService = context.getBean(UserServiceImpl.class);PageInfo<UserDO> pageInfo = userService.pageUser(1, 10);log.info("pageInfo:{}", JSON.toJSONString(pageInfo));}// ================================= mapper test =================================@Testpublic void getUserByIdTest() {UserMapper userMapper = context.getBean(UserMapper.class);UserDO userDO = userMapper.getUserById(1L);log.info("userDO", JSON.toJSONString(userDO));}@Testpublic void listAllUserTest() {userMapperTest();// userServiceTest();}private void userServiceTest() {UserService userService = context.getBean(UserServiceImpl.class);List<UserDO> userDOS = userService.listAllUser();System.out.println("userService userDOS = " + userDOS);}private void userMapperTest() {UserMapper userMapper = context.getBean(UserMapper.class);List<UserDO> userDOS = userMapper.listAllUser();System.out.println("userMapper userDOS = " + userDOS);}}