标签:mybatis
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
原文地址:http://shamrock.blog.51cto.com/2079212/1559084