后端接口开发指南:MyBatis 代理开发的软件测试学习笔记
发表时间: 2024-05-11 10:34
本文转自测试人社区,原文链接:jck28 - 小柒 - 后端接口开发 - MyBatis 代理开发 - 学习笔记 - 测试人社区
package com.ceshiren.dao;import com.ceshiren.dao.entity.TestUser;public interface UserMapper { TestUser findById(int id);}
<?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"><!-- namespace:命名空间,与sql标签的id属性共同构成唯一标识,代理开发方式:应与接口全限定类名一致--><mapper namespace="com.ceshiren.dao.UserMapper"> <select id ="findById" parameterType="int" resultType="TestUser"> SELECT * FROM test_user WHERE id=${id} </select></mapper>
<?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> <!--配置连接数据库的环境--> <!-- 加载外部的配置文件--> <properties resource="jdbc.properties"/><!-- 设置别名--> <typeAliases><!-- 单个实体类的别名--><!-- <typeAlias type="com.ceshiren.dao.entity.TestUser" alias="user1"/>--><!-- 多个实体类的情况下,用包名+类名的方式,推荐这种方式--> <package name="com.ceshiren.dao.entity"/> </typeAliases><!-- default - 默认环境配置--> <environments default="development"> <environment id="development"><!-- transactionManager - 事务管理器--> <transactionManager type="JDBC"/><!-- dataSource - 数据库的连接池 POOLED - 表示使用mybatis的连接池; UNPOOLED - 不用mybatis的连接池,每次都用新的连接 --> <dataSource type="POOLED"><!-- 配置数据库连接属性--> <property name="driver" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </dataSource> </environment> </environments><!-- mapper映射关系引入--> <mappers><!-- <mapper resource="TestUserMapping.xml"/>--> <mapper resource="com/ceshiren/dao/UserMapper.xml"/> </mappers></configuration>
package com.ceshiren.dao;import com.ceshiren.dao.entity.TestUser;import org.apache.ibatis.io.Resources;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;import org.junit.jupiter.api.Test;import java.io.IOException;import java.io.InputStream;import java.util.List;import static org.junit.jupiter.api.Assertions.*;class IUserDaoTest { @Test void findById() throws IOException { InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml"); SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream); SqlSession sqlSession = build.openSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); TestUser testUser = mapper.findById(395); System.out.println(testUser); sqlSession.close(); }}