首页 > 代码库 > Mybatis学习笔记-CURD(基于注解的方式)
Mybatis学习笔记-CURD(基于注解的方式)
User.java实体类
public class User { private int id; private String username; private int age; //.. }
UserMapper.java接口
public interface UserMapper { @Insert("insert into users(username, age) values(#{username}, #{age})") public int insertUser(User user); @Delete("delete from users where id = #{id}") public int deleteUserById(int id); @Update("update users set username = #{username}, age = #{age} where id = #{id}") public int updateUser(User user); @Select("select * from users where id = #{id}") public User getUserById(int id); @Select("select * from users") public List<User>getAllUser(); }
将接口类注册到conf.xml文件中
<mappers> <mapper class="com.mybatis.test01.UserMapper"/> </mappers>
测试方法
@Test public void testInsert() { SqlSessionFactory factory = MybatisUtil.getFactory(); SqlSession session = factory.openSession(true); UserMapper mapper = session.getMapper(UserMapper.class); User user = new User(); user.setUsername("test01"); user.setAge(22); int insert = mapper.insertUser(user); System.out.println(insert); session.close(); } @Test public void testDelete() { SqlSessionFactory factory = MybatisUtil.getFactory(); SqlSession session = factory.openSession(true); UserMapper mapper = session.getMapper(UserMapper.class); int delete = mapper.deleteUserById(3); System.out.println(delete); session.close(); } @Test public void testUpdate() { SqlSessionFactory factory = MybatisUtil.getFactory(); SqlSession session = factory.openSession(true); UserMapper mapper = session.getMapper(UserMapper.class); User user = new User(); user.setUsername("umgsai"); user.setAge(25); user.setId(2); int update = mapper.updateUser(user); System.out.println(update); session.close(); } @Test public void testSelect() { SqlSessionFactory factory = MybatisUtil.getFactory(); SqlSession session = factory.openSession(true); UserMapper mapper = session.getMapper(UserMapper.class); User user = mapper.getUserById(2); System.out.println(user); session.close(); } @Test public void testSelectAll(){ SqlSessionFactory factory = MybatisUtil.getFactory(); SqlSession session = factory.openSession(true); UserMapper mapper = session.getMapper(UserMapper.class); List<User>users = mapper.getAllUser(); System.out.println(users); session.close(); }
本文出自 “阿凡达” 博客,请务必保留此出处http://shamrock.blog.51cto.com/2079212/1559084
Mybatis学习笔记-CURD(基于注解的方式)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。