Spring Mybatis整合+单元测试
PO
java
@Data
public class User {
private Integer id;
private String username;
private String password;
private String salt;
private String token;
private Byte isEnabled;
private Date createTime;
private Date modifiedTime;
}
DAO
java
public interface UserMapper {
List<User> selectAllUser();
}
Service
java
public interface UserService {
List<User> selectAllUser();
}
Impl
java
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public List<User> selectAllUser() {
return userMapper.selectAllUser();
}
}
mapper.xml
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="cn.cjf.tt.dao.UserMapper">
<resultMap id="BaseResultMap" type="cn.cjf.tt.po.User">
<id column="id" jdbcType="INTEGER" property="id" />
<result column="username" jdbcType="VARCHAR" property="username" />
<result column="password" jdbcType="VARCHAR" property="password" />
<result column="salt" jdbcType="VARCHAR" property="salt" />
<result column="token" jdbcType="VARCHAR" property="token" />
<result column="is_enabled" jdbcType="TINYINT" property="isEnabled" />
<result column="create_time" jdbcType="TIMESTAMP" property="createTime" />
<result column="modified_time" jdbcType="TIMESTAMP" property="modifiedTime" />
</resultMap>
<sql id="Base_Column_List">
id, username, password, salt, token, is_enabled, create_time, modified_time
</sql>
<select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from sys_user
where id = #{id,jdbcType=INTEGER}
</select>
<select id="selectAllUser" resultMap="BaseResultMap">
SELECT <include refid="Base_Column_List"/> FROM sys_user;
</select>
</mapper>
mybatis.xml
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>
<!-- 使全局的映射器启用或禁用缓存 -->
<setting name="cacheEnabled" value="true" />
<!-- 允许JDBC 支持自动生成主键 -->
<setting name="useGeneratedKeys" value="true" />
<!-- 配置默认的执行器.SIMPLE就是普通执行器;REUSE执行器会重用预处理语句(prepared statements);BATCH执行器将重用语句并执行批量更新 -->
<setting name="defaultExecutorType" value="SIMPLE" />
<!-- 指定 MyBatis 所用日志的具体实现 -->
<setting name="logImpl" value="SLF4J" />
<!-- 使用驼峰命名法转换字段 -->
<!-- <setting name="mapUnderscoreToCamelCase" value="true"/> -->
</settings>
</configuration>
druid.properties
properties
druid.driver =com.mysql.cj.jdbc.Driver
druid.url = jdbc:mysql://localhost:3306/test
druid.userName = root
druid.password = 123456
#初始化连接数
druid.pool.init=3
#高峰期过后,保留连接吃的个数
druid.pool.minIdle = 5
#高峰期,最大能创建连接的个数
druid.pool.MaxActive = 20
#等待的时间
druid.pool.timeout = 30
spring.xml
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: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/context
http://www.springframework.org/schema/context/spring-context.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">
<!--
在配置数据源之前,我们首先进行注解配置的声明以及使用<Context:property-placeholder>进行外部文件的引用,
之后在使用<bean>标签进行数据源的配置,然后再使用${}符号记性属性值的注入即可;
-->
<!--声明使用注解配置-->
<Context:annotation-config/>
<!--声明Spring工厂注解的扫描范围-->
<Context:component-scan base-package="cn.cjf"/>
<!--引用外部文件-->
<Context:property-placeholder location="druid.properties"/>
<!--配置DruidDataSources-->
<bean id="druidDataSources" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${druid.driver}"/>
<property name="url" value="${druid.url}"/>
<property name="username" value="${druid.userName}"/>
<property name="password" value="${druid.password}"/>
<property name="initialSize" value="${druid.pool.init}"/>
<property name="minIdle" value="${druid.pool.minIdle}"/>
<property name="maxActive" value="${druid.pool.MaxActive}"/>
<property name="maxWait" value="${druid.pool.timeout}"/>
</bean>
<!--
配置sqlSessionFactory
首先需要依赖spring容器进行mybatis的sqlSessionFactory的创建,然后再进行数据源的配置,
在配置sqlSessionFactory过程中可以对mapper映射文件进行配置,
也可以进行配置需要定义的实体类别名、以及引入mybatis-config.xml(mybatis主配置文件)等操作~
-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--配置数据源-->
<property name="dataSource" ref="druidDataSources"/>
<!--配置mapper的路径-->
<property name="mapperLocations" value="classpath*:mapper/*Mapper.xml">
</property>
<!--配置需要定义别名的实体类的包-->
<property name="typeAliasesPackage" value="cn.cjf.tt.po"/>
<!--配置需要mybatis的主配置文件-->
<property name="configLocation" value="mybatis-config.xml"/>
</bean>
<!--
配置MapperScannerConfigurer
在配置MapperScannerConfigurer中主要是加载dao包中的所有dao接口,
通过sqlSessionFactory获取sqlSession,然后创建所有dao接口对象,存储在spring容器
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<property name="basePackage" value="cn.cjf.tt.dao"/>
</bean>
<!--
整合Aop配置:
使用spring整合Aop配置,使用spring提供的事务管理切面类,完成dao中的CRUD操作的事务管理。步骤如下:
将spring提供的事务管理配置给spring
通过spring jdbc提供的<tx>标签,声明事物的管理策略(设置事务的隔离级别以及传播机制)
将事务管理策略以Aop配置,应用于Dao层的操作方法
-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="druidDataSources"/>
</bean>
<!--
声明事务策略
通过Spring jdbc提供的<tx>标签声明事物的管理策略,并给事务设置隔离级别以及传播机制
-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="Insert*" isolation="REPEATABLE_READ" propagation="REQUIRED"/>
<tx:method name="Update*" isolation="REPEATABLE_READ" propagation="REQUIRED"/>
<tx:method name="Delete*" isolation="REPEATABLE_READ" propagation="REQUIRED"/>
<tx:method name="Query*" isolation="REPEATABLE_READ" propagation="SUPPORTS"/>
</tx:attributes>
</tx:advice>
<!--
Aop事务配置
将事务管理策略以Aop配置,应用于Dao层的操作方法(主要是应用于ServiceI方法(ServiceImp)),使用<aop:config>标签;在标签内,定义切点。
-->
<aop:config>
<aop:pointcut id="crud" expression="execution(* cn.cjf.tt.service.impl.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="crud"/>
</aop:config>
</beans>
单元测试
java
public class UserDaoTest {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
@Test
public void selectAllUser() {
UserService userDao = context.getBean(UserService.class);
List<User> users = userDao.selectAllUser();
for (User i : users) {
System.out.println(i);
}
}
}
java
// 使用Spring整合Junit专用的类加载器
@RunWith(SpringJUnit4ClassRunner.class)
// 加载配置文件或者配置类
//@ContextConfiguration(classes = {SpringConfiguration.class}) //加载配置类
@ContextConfiguration(locations = {"classpath:spring.xml"})//加载配置文件
public class UserTest {
@Autowired
private UserService userService;
@Test
public void selectAllUser() {
List<User> users = userService.selectAllUser();
for (User i : users) {
System.out.println(i);
}
}
}