测试顺序:
在接口中编写方法→在与该接口绑定的mapper中写对应操作→junit测试 在这里我用的接口类为UserMapper,对应绑定的xml为UserMapper.xml,代码如下
UserMapper:
public interface UserMapper {
List<User> getAlluser();
User getUserById(int id);
int insertUser(User user);
int updateUser(User user);
int deleteUser(int id);
}
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="com.chong.dao.UserMapper">
<select id="getAlluser" resultType="com.chong.pojo.User">
select * from mybatis.user
</select>
<select id="getUserById" parameterType="int" resultType="com.chong.pojo.User">
select * from mybatis.user where id = #{id}
</select>
<insert id="insertUser" parameterType="com.chong.pojo.User" >
insert into mybatis.user (id, name, pwd) values (#{id},#{name},#{pwd});
</insert>
<update id="updateUser" parameterType="com.chong.pojo.User">
update mybatis.user set name=#{name},pwd=#{pwd} where id = #{id};
</update>
<delete id="deleteUser" parameterType="int">
delete from mybatis.user where id = #{id};
</delete>
</mapper>
junit测试类:
public class UserMapperTest {
@Test
public void test(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> alluser = userMapper.getAlluser();
for (User user: alluser) {
System.out.println(user.toString());
}
sqlSession.close();
}
@Test
public void testgetUserById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
try{
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User userById = userMapper.getUserById(2);
System.out.println(userById.toString());
}catch (Exception e){
e.printStackTrace();
}finally {
sqlSession.close();
}
}
@Test
public void testinsertUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper insertuser = sqlSession.getMapper(UserMapper.class);
int i = insertuser.insertUser(new User(6, "东皇太一", "123456"));
if (i > 0) {
System.out.println("用户插入成功");
}else {
System.out.println("用户插入失败");
}
sqlSession.commit();
sqlSession.close();
}
@Test
public void testupdateUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
userMapper.updateUser(new User(4,"姚","11111111"));
sqlSession.commit();
sqlSession.close();
}
@Test
public void deleteUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.deleteUser(5);
sqlSession.commit();
sqlSession.close();
}
}
|