注解开发需要删除IUserDao.xml文件(即mappers文件)。
以下是注解的形式:
省略User.java
IUserDao.java
- CRUD一共有四个注解 @Select @Insert @Update @Delete
package com.jh.dao;
import com.jh.domain.User;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import java.util.List;
/**
* 用户的持久层接口
* 在mybatis中针对,CRUD一共有四个注解
* @Select @Insert @Update @Delete
**/
public interface IUserDao {
/** 1.查询所有用户 */
@Select("select * from user")
List<User> findAll();
/** 2.保存用户 */
@Insert("insert into user(username,address,sex,birthday)values(#{username},#{address},#{sex},#{birthday})")
void saveUser(User user);
/** 3.更新操作*/
@Update("update user set username=#{username},sex=#{sex},address=#{address} where id=#{id}")
void updateUser(User user);
/**
* 4.删除用户
* @param userId
*/
@Delete("delete from user where id=#{id} ")
void deleteUser(Integer userId);
/**
* 5.根据id查询用户
* @param userId
* @return
*/
@Select("select * from user where id=#{id} ")
User findById(Integer userId);
/**
* 6.根据用户名称模糊查询
* @param username
* @return
*/
// @Select("select * from user where username like #{username} ")
@Select("select * from user where username like '%${value}%' ")
List<User> findUserByName(String username);
/**
* 7.查询总用户数量
* @return
*/
@Select("select count(*) from user ")
int findTotalUser();
}
测试CRUD部分代码:AnnotationCRUDTest
/**
* CRUD注解测试
* */
public class AnnotationCRUDTest {
private InputStream in;
private SqlSessionFactory factory;
private SqlSession sqlSession;
private IUserDao userDao;
@Before
public void init()throws Exception{
in= Resources.getResourceAsStream("SqlMapConfig.xml");
factory=new SqlSessionFactoryBuilder().build(in);
sqlSession=factory.openSession();
userDao=sqlSession.getMapper(IUserDao.class);
}
@After
public void destroy() throws IOException {
sqlSession.commit();
sqlSession.close();
in.close();
}
/** 保存用户操作*/
@Test
public void testSave(){
User user=new User();
user.setUsername("注解测试CRUD");
user.setAddress("安徽省合肥市");
user.setSex("男");
user.setBirthday(new Date());
userDao.saveUser(user);
}
/** 更新用户操作*/
@Test
public void updateUser(){
User user=new User();
user.setId(50);
user.setUsername("注解测试CRUD");
user.setAddress("安徽省北市");
user.setSex("男");
user.setBirthday(new Date());
userDao.updateUser(user);
}
/** 删除操作*/
@Test
public void testDelete(){
userDao.deleteUser(50);
}
/** 根据id查询操作*/
@Test
public void testFindOne(){
User user = userDao.findById(57);
System.out.println(user);
}
/** 模糊查询操作*/
@Test
public void testFindByName(){
// List<User> users = userDao.findUserByName("%mybatis%");
List<User> users = userDao.findUserByName("mybatis");
for(User user : users){
System.out.println(user);
}
}
/** 查询总记录*/
@Test
public void testFindTotal(){
int total = userDao.findTotalUser();
System.out.println(total);
}
}