继续上一节
1.sql映射文件
在config源文件夹下创建mybatis包,在mybatis包下创建和User类同名的xml文件,文件名称:
- User.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">
<!-- namespace命名空间,隔离SQL语句 -->
<mapper namespace="user">
</mapper>
2.加载映射文件
修改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>
<!-- 和spring整合后 environments配置将废除 -->
<environments default="development">
<environment id="development">
<!-- 使用jdbc事务管理 -->
<transactionManager type="JDBC" />
<!-- 数据库连接池 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url"
value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8" />
<property name="username" value="root" />
<property name="password" value="root" />
</dataSource>
</environment>
</environments>
<mappers>
<!-- 加载映射文件 ,mapper url=配置文件引入从本地磁盘引入 -->
<mapper resource="mybatis/User.xml"/>
</mappers>
</configuration>
3.在User.xml写SQL语句
<?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语句 -->
<mapper namespace="user">
<!-- id:sql唯一标识
parameterType 入参类型
resultType 返回结果类型-->
<select id="getUserByid" parameterType="int" resultType="com.mybatis.domain.User">
SELECT
`id`,
`username`,
`birthday`,
`sex`,
`address`
FROM `user`
WHERE id=#{id}
</select>
</mapper>
4.编写测试方法
package com.mybatis.test;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
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.Test;
import com.mybatis.domain.User;
public class MybatitsTest {
@Test
public void testGetUserById() throws Exception {
//创建SqlSessionFactoryBuilder对象
SqlSessionFactoryBuilder s=new SqlSessionFactoryBuilder();
//配置输入流
InputStream input=Resources.getResourceAsStream("SqlMapConfig.xml");
//通过输入流创建创建SqlSessionFactory对象
SqlSessionFactory sql=s.build(input);
//创建SqlSession对象
SqlSession ss=sql.openSession();
//查询,参数一SQL id 参数二 入参
User user= ss.selectOne("user.getUserByid", 1);
System.out.println(user);
//释放资源
ss.close();
}
}