mybatis测试:
数据库结构
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="12345" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="sqlMap/User.xml"></mapper>
</mappers>
</configuration>
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="test">
<!-- id:statement的id 或者叫做sql的id-->
<!-- parameterType:声明输入参数的类型 -->
<!-- resultType:声明输出结果的类型,应该填写pojo的全路径 -->
<!-- #{}:输入参数的占位符,相当于jdbc的? -->
<!--${}:字符串拼接-->
<select id="queryUserById" parameterType="int" resultType="cn.itcast.po.User">
SELECT * FROM `user` WHERE id = #{id}
</select>
<!--如果用#{},就可以随意取名,但是必须按下面格式写字符串条件,如果用${},则取名必须为value-->
<select id="queryUserByUsername" parameterType="String" resultType="cn.itcast.po.User">
-- SELECT * FROM `user` WHERE username LIKE '%${value}%'
SELECT * FROM `user` WHERE username LIKE "%"#{v}"%"
</select>
</mapper>
单元测试代码处:
private SqlSessionFactory sqlSessionFactory = null;
@Before
public void init() throws Exception {
// 1. 创建SqlSessionFactoryBuilder对象
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
// 2. 加载SqlMapConfig.xml配置文件
InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
// 3. 创建SqlSessionFactory对象
this.sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
}
@Test
public void testQueryUserById() throws Exception {
// 5. 执行SqlSession对象执行查询,获取结果User
// 第一个参数是User.xml的statement的id,第二个参数是执行sql需要的参数;
SqlSession sqlSession = sqlSessionFactory.openSession();
Object user = sqlSession.selectOne("queryUserById", 22);
// 6. 打印结果
System.out.println(user);
// 7. 释放资源
sqlSession.close();
}
@Test
public void testQueryUserByUsername() throws Exception {
// 5. 执行SqlSession对象执行查询,获取结果User
// 第一个参数是User.xml的statement的id,第二个参数是执行sql需要的参数;
SqlSession sqlSession = sqlSessionFactory.openSession();
List<Object> list = sqlSession.selectList("test.queryUserByUsername", "五");
// 6. 打印结果
System.out.println(list);
// 7. 释放资源
sqlSession.close();
}
网友评论