Dao层:
1 public interface IUserDao { 2 3 /** 4 * 查询所有结果 5 * @return 6 */ 7 @Select("select * from user") 8 List<User> findAll(); 9 10 /** 11 * 保存用户 12 * @param user 13 */ 14 @Insert("insert into user(username,address,sex,birthday) values(#{username},#{address},#{sex},#{birthday})") 15 void saveUser(User user); 16 17 /** 18 * 更新用户 19 * @param user 20 */ 21 @Update("update user set username = #{username},address = #{address},sex = #{sex},birthday = #{birthday} where id = #{id}") 22 void updateUser(User user); 23 24 /** 25 * 删除用户 26 * @param id 27 */ 28 @Delete("delete from user where id = #{id}") 29 void deleteUser(Integer id); 30 31 /** 32 * 根据id查询用户 33 * @param userId 34 * @return 35 */ 36 @Select("select * from user where id = #{id}") 37 User findById(Integer userId); 38 39 /** 40 * 根据用户模糊查询 41 * @param username 42 * @return 43 */ 44 // @Select("select * from user where username like #{username}") //字符串拼接 45 @Select("select * from user where username like '%${value}%'") //参数占位符 46 List<User> findUserByName(String username); 47 48 /** 49 * 查询总用户数量 50 * @return 51 */ 52 @Select("select count(*) from user") 53 int findTotalUser(); 54 55 }
test:
1 public class AnnotationCRUDTest { 2 3 private InputStream in; 4 private SqlSessionFactory factory; 5 private SqlSession session; 6 private IUserDao userDao; 7 8 @Before 9 public void init() throws IOException { 10 in = Resources.getResourceAsStream("SqlMapConfig.xml"); 11 factory = new SqlSessionFactoryBuilder().build(in); 12 session = factory.openSession(); 13 userDao = session.getMapper(IUserDao.class); 14 } 15 16 @After 17 public void destory() throws IOException { 18 session.commit(); 19 session.close(); 20 in.close(); 21 } 22 23 @Test 24 public void testSave(){ 25 User user = new User(); 26 user.setUsername("flypig"); 27 user.setAddress("中国"); 28 29 userDao.saveUser(user); 30 } 31 32 @Test 33 public void testUpdate(){ 34 User user = new User(); 35 user.setId(49); 36 user.setUsername("flypighhh"); 37 user.setAddress("China"); 38 user.setSex("男"); 39 user.setBirthday(new Date()); 40 41 userDao.updateUser(user); 42 } 43 44 @Test 45 public void testDelete(){ 46 userDao.deleteUser(49); 47 } 48 49 @Test 50 public void testFindOne(){ 51 User user = userDao.findById(48); 52 System.out.println(user); 53 } 54 55 @Test 56 public void testFindUserByName(){ 57 //List<User> users = userDao.findUserByName("%王%"); 58 List<User> users = userDao.findUserByName("王"); 59 for (User user : users) { 60 System.out.println(user); 61 } 62 } 63 64 @Test 65 public void testFindTotal(){ 66 int total = userDao.findTotalUser(); 67 System.out.println(total); 68 } 69 70 }