源码剖析-源码环境搭建
# 3.1 源码环境搭建
- mybatis源码地址:https://github.com/mybatis/mybatis-3
# 3.2 源码导入&编译
# 3.3 编写测试代码
# 3.3.1 配置sqlMapConfig.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>
<!--第一部分:数据源配置-->
<environments default="development">
<environment id="development">
<!-- 使用jdbc事务管理 -->
<transactionManager type="JDBC" />
<!-- 数据库连接池 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver" />
<property name="url"
value="jdbc:mysql:///zdy_mybatis?useSSL=false&characterEncoding=UTF-8&serverTimezone=UTC" />
<property name="username" value="root" />
<property name="password" value="root" />
</dataSource>
</environment>
</environments>
<!--第二部分:引入映射配置文件-->
<mappers>
<mapper resource="mapper/UserMapper.xml"></mapper>
</mappers>
</configuration>
# 3.3.2 配置UserMapper.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="user">
<select id="findUserById" parameterType="int" resultType="com.itheima.pojo.User">
SELECT id,username FROM user WHERE id = #{id}
</select>
</mapper>
# 3.3.3 编写User类
package com.itheima.pojo;
import lombok.Data;
@Data
public class User {
// ID标识
private Integer id;
// 用户名
private String username;
}
# 3.3.5 编写测试类
public class MybatisTest {
@Test
public void test1() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
User user = sqlSession.selectOne("user.findUserById", user1);
System.out.println(user);
System.out.println("MyBatis源码环境搭建成功...");
sqlSession.close();
}
}
输出:
上次更新: 2023/08/10, 16:25:16