我们根据上篇文章搭建的mybatis环境操作,如果没有搭建环境的可以去上篇博客(第一个mybatis程序)查看。
1、namespace
namespace中的包名要和Dao/mapper接口的包名一致!
2、select
选择,查询语句;
id:就是对应的namespace中的方法名;
resultType:Sql语句执行的返回值!
parameterType:参数类型!
1、编写接口
//根据id查询用户 User getUserById(int id);
2、编写mapper中对应的sql语句
<select id = "getUserById" resultType="com.allen.pojo.User" parameterType = "int"> select * from mybatis.user where id = #{id}; </select>
3、测试
@Test public void getUserById(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserDao userDao = sqlSession.getMapper(UserDao.class); User user = userDao.getUserById(1); System.out.println(user); sqlSession.close(); }
3、insert
插入,新增语句
//新增用户 int addUser(User user);
<insert id = "addUser" parameterType = "com.allen.pojo.User"> insert into mybatis.user(`id`, `name`, `pwd`) values (#{id}, #{name}, #{pwd}); </insert>
@Test public void addUser(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserDao userDao = sqlSession.getMapper(UserDao.class); int allen = userDao.addUser(new User(4, "allen", "123456")); if(allen > 0){ System.out.println("新增成功"); sqlSession.commit(); } sqlSession.close(); }
4、update
修改,更新语句
//修改用户 int updateUser(User user);
<update id = "updateUser" parameterType="com.allen.pojo.User"> update mybatis.user set `name` = #{name}, `pwd` = #{pwd} where id = #{id}; </update>
@Test public void updateUser(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserDao userDao = sqlSession.getMapper(UserDao.class); int liqinglin = userDao.updateUser(new User(4, "liqinglin", "654321")); if (liqinglin > 0){ System.out.println("修改成功"); sqlSession.commit(); } sqlSession.close(); }
5、delete
删除语句
//删除用户 int deleteUser(int id);
<delete id = "deleteUser" parameterType = "int"> delete from mybatis.user where id = #{id}; </delete>
@Test public void deleteUser(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserDao userDao = sqlSession.getMapper(UserDao.class); int i = userDao.deleteUser(4); if(i > 0){ System.out.println("删除成功"); sqlSession.commit(); } sqlSession.close(); }
注意:insert、update、delete要提交事务:sqlSession.commit();