接上篇:Mybatis入门
这里的所有测试没有使用注解
上篇使用了查询语句
<mapper namespace="cn.sjcup.Mapper.UserMapper">
<select id="getUserList" resultType="cn.sjcup.pojo.User">
select * from mybatis.user
select>
mapper>
根据id查询用户
增加了一个需求,在本示例中,只需要修改三处代码,对应三步操作:1.编写接口;2.编写mapper中的sql语句;3.测试
UserMapper
public interface UserMapper {
//查询全部用户
List<User> getUserList();
//根据id查询用户
User getUserById(int id);
}
UserMapper.xml
<select id="getUserById" parameterType="int" resultType="cn.sjcup.pojo.User">
select * from mybatis.user where id =#{id}
select>
Test
@Test
public void getUserById(){
//1.获取sqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
//2.执行sql
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user1 = mapper.getUserById(1);
System.out.println(user1);
//3.关闭sqlsession
sqlSession.close();
}
输出结果:
> User{id=1, name='张三', pwd='123456'}
增、删、改需要添加事务的提交
UserMapper
//插入一个用户
int addUser(User user);
UserMapper.xml
<insert id="addUser" parameterType="cn.sjcup.pojo.User" >
insert into mybatis.user(id, name, pwd) values (#{id},#{name},#{pwd});
insert>
Test
//增删改需要提交事务
@Test
public void addUser(){
//1.获取sqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
//2.执行sql
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int result = mapper.addUser(new User(4, "小明", "124578"));
//3. 提交事务
sqlSession.commit();
//4.关闭sqlsession
sqlSession.close();
}
UserMapper
//修改一个用户
int updateUser(User user);
UserMapper.xml
<update id="updateUser" parameterType="cn.sjcup.pojo.User">
update mybatis.user set name=#{name}, pwd=#{pwd} where id=#{id};
update>
Test
@Test
public void updateUser(){
//1.获取sqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
//2.执行sql
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.updateUser(new User(2, "小红", "789"));
//3. 提交事务
sqlSession.commit();
//4.关闭sqlsession
sqlSession.close();
}
UserMapper
//删除一个用户
int deleteUser(int id);
UserMapper.xml
<delete id="deleteUser" parameterType="int">
delete from mybatis.user where id=#{id}
delete>
Test
@Test
public void deleteUser(){
//1.获取sqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
//2.执行sql
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.deleteUser(4);
//3. 提交事务
sqlSession.commit();
//4.关闭sqlsession
sqlSession.close();
}
在上述增删查改的测试中,使用到了User
类,这些也可以使用map
,相比而言,使用map更加灵活,但也后期维护需要了解每个参数代表的含义,增加了维护成本。
修改
UserMapper
int updateUser2(Map<String, Object> map);
UserMapper.xml
<update id="updateUser2" parameterType="map">
update mybatis.user set pwd=#{password} where id=#{id};
update>
Test
//测试map
@Test
public void updateUser2(){
//1.获取sqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
//2.执行sql
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Map<String, Object> map = new HashMap<String, Object>();
map.put("id", 2);
map.put("password", 11111);
mapper.updateUser2(map);
//3. 提交事务
sqlSession.commit();
//4.关闭sqlsession
sqlSession.close();
}