首先mybatis配置文件中注册mapper.class,实质用反射机制实现
底层用的动态代理注解需要在接口上实现,脱离mapper.xml
1.查询方法mapper的编写
@Select("SELECT * FROM USER") ListgetUser(); @Insert("insert into ljqdb.user (username, password) VALUES (#{name},#{pass})") int addUserMap(Map map); @Delete(" delete from ljqdb.user where id = #{id}") int deleteUser(int id); @Update("update ljqdb.user set username=#{username},password=#{password} where id = #{id}") int upUser(User user);
测试类的编写
public class UserTest { @Test public void upUser() { SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user = new User(3, "我爱你", "123"); mapper.upUser(user); sqlSession.commit(); sqlSession.close(); } @Test public void delUser() { SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); int id = 6; mapper.deleteUser(id); sqlSession.commit(); sqlSession.close(); } @Test public void add(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); //创建map接收 Mapmap = new HashMap<>(); map.put("name", "麻子黄"); map.put("pass", "xiao"); mapper.addUserMap(map); //提交事务 sqlSession.commit(); //关闭sqlSession实例 sqlSession.close(); } @Test public void getUser(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); List user = mapper.getUser(); for (User user1 : user) { System.out.println(user1); } sqlSession.close(); } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)