3.增删改查的实现(1)
3.1 只需要更改接口,配置文件和测试类,工具类和实体类不用再变。 写接口---在UserMapper中 写sql语句---UserMapper.xml中 写测试类---UserDaoTest中 namespace中的包名要和接口中的包名一致 注意事项 增删改要提交事务 sqlSession.commit(); 标签不要匹配错 核心配置文件必须严格正确 3.2 xml中的语句: id:对应namespace中的方法名 resultType:SQL语句的返回值 parameterType:要传的参数的类型 编写接口 //查询所有用户 List<User> getUserList(); //根据id查询用户 User getUserById(int id); //插入用户 int addUser(User user); //修改用户 int updateUser(User user); //删除用户 int deleteUser(int id); 编写配置文件(写SQL语句) <mapper namespace="com.mu.dao.UserMapper"> <select id="getUserList" resultType="com.mu.pojo.User"> select * from user </select> <select id="getUserById" resultType="com.mu.pojo.User" parameterType="int"> select * from user where id = #{id} </select> <insert id="addUser" parameterType="com.mu.pojo.User"> insert into mybatis.user(id,name,pwd) values(#{id},#{name},#{pwd}); </insert> <update id="updateUser" parameterType="com.mu.pojo.User"> update mybatis.user set name=#{name},pwd=#{pwd} where id=#{id}; </update> <delete id="deleteUser" parameterType="int"> delete from user where id = #{id}; </delete> </mapper> 编写类 package com.mu.dao; import com.mu.pojo.User; import com.mu.utils.MybatisUtils; import org.apache.ibatis.session.SqlSession; import org.junit.Test; import java.util.List; public class UserDaoTest { @Test public void test(){ //第一步:获取SqlSession对象 SqlSession sqlSession = MybatisUtils.getSqlSession(); //方式一:getMapper UserMapper mapper = sqlSession.getMapper(UserMapper.class); List<User> userList = mapper.getUserList(); for (User user : userList) { System.out.println(user); } sqlSession.close();//关闭 } @Test public void getUserById(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user = mapper.getUserById(1); System.out.println(user); sqlSession.close(); } @Test public void addUser(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); int res = mapper.addUser (new User(4,"aaa","aaa")); sqlSession.commit(); sqlSession.close(); } @Test public void updateUser(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); int res = mapper.updateUser(new User(4,"bbb","bbb")); sqlSession.commit(); sqlSession.close(); } @Test public void deleteUser(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); int res = mapper.deleteUser(4); sqlSession.commit(); sqlSession.close(); } }