更新用户
在UserMapper接口中定义方法
int updateUser();
在UserMapper.xml文件中写
<update id="updateUser"> update user set name = "张三" where id = "1" </update>
*id后面跟方法名
在测试类代码中
@Test public void testUpdate(){ SqlSession sqlSession = SqlSessionUtil.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); int i = mapper.updateUser(); System.out.println("i = " + i); sqlSession.close(); }
*注释部分在MyBatis测试代码,MyBatis入门----优化代码 优化1中
删除用户
和更新用户步骤一样
在UserMapper接口中定义方法
int deleteUser();
在UserMapper.xml文件中写
<delete id="deleteUser"> delete from user where id = 1 </delete>
在测试类代码中
@Test public void DeleteUser(){ SqlSession sqlSession = SqlSessionUtil.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); int i = mapper.deleteUser(); System.out.println("i = " + i); sqlSession.close(); }
查询用户
查询单条记录
在UserMapper接口中定义方法。返回类型为User
User queryUserById();
在UserMapper.xml文件中写
<select id="queryUserById" resultType="com.cdd.entity.User"> select * from user where id = 1 </select>
*查询要写返回结果类型,不然运行报错
在测试类代码中
@Test public void testQueryUserById(){ SqlSession sqlSession = SqlSessionUtil.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user = mapper.queryUserById(); sqlSession.close(); System.out.println("user = " + user); }
查询多条记录
在UserMapper接口中定义方法。返回类型为List集合
List<User> queryAllUser();
在UserMapper.xml文件中写
<select id="queryAllUser" resultType="com.cdd.entity.User"> select * from user </select>
在测试类代码中
@Test public void testQueryUsers(){ SqlSession sqlSession = SqlSessionUtil.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); List<User> userList = mapper.queryAllUser(); sqlSession.close(); System.out.println("userList = " + userList); }
*查询标签select必须设置resultType或resultMap,用于设置实体类和数据库表的映射关系
*resultType:自动映射,用于属性名和表中字段名一致的情况
*resultMap:自定义映射,用于一对多或多对一或字段名和属性名不一致的情况