Day_06
Mybatis注解的用法;不推荐使用;
与XML类似,不再XML中写SQL,改成在接口的方法的注解里写SQL;用法类似;
1. 不使用XML而是使用@注解在IDAO的方法上面,定义SQL语句
目录结构没有IDAO接口的XML

2. 定义CRUD方法
IUserDao接口
/**
* @author A
* User的持久层接口
*/
//开启二级缓存 @CacheNamespace(blocking = true)
@CacheNamespace(blocking = true)
public interface IUserDao {
/**
* 查询所有User表的记录-操作
* @return
*/
@Select("SELECT * FROM user")
List<User> findAll();
/**
* 保存用户
* @param user
*/
@Insert("insert into user(username,address,sex,birthday)values(#{username},#{address},#{sex},#{birthday})")
void saveUser(User user);
/**
* 更新用户
* @param user
*/
@Update("update user set username=#{username},sex=#{sex},birthday=#{birthday},address=#{address} where id=#{id}")
void updateUser(User user);
/**
* 删除用户
* @param userId
*/
@Delete("delete from user where id=#{id} ")
void deleteUser(Integer userId);
/**
* 根据id查询用户
* @param userId
* @return
*/
@Select("select * from user where id=#{id} ")
User findById(Integer userId);
/**
* 根据用户名称模糊查询
* @param username
* @return
* // @Select("select * from user where username like #{username} ")
*/
@Select("select * from user where username like '%${value}%' ")
List<User> findUserByName(String username);
/**
* 查询总用户数量
* @return
*/
@Select("select count(*) from user ")
int findTotalUser();
}
3. 一对一、一对多查询
//添加resultMap(因为多了List<Account>属性),一对一/多
/**
* 查询所有用户:一对多
* @return
*/
@Select("select * from user")
@Results(id="userMap",value={
@Result(id=true,column = "id",property = "userId"),
@Result(column = "username",property = "userName"),
@Result(column = "address",property = "userAddress"),
@Result(column = "sex",property = "userSex"),
@Result(column = "birthday",property = "userBirthday"),
@Result(property = "accounts",column = "id",
many = @Many(select = "com.ming.dao.IAccountDao.findAccountByUid",
fetchType = FetchType.LAZY))
})
List<User> findAll1();
/**
* 根据id查询用户
* @param userId
* @return
*/
@Select("select * from user where id=#{id} ")
@ResultMap("userMap")
User findById1(Integer userId);
/**
* 根据用户名称模糊查询
* @param username
* @return
*/
@Select("select * from user where username like #{username} ")
@ResultMap("userMap")
List<User> findUserByName1(String username);
4. 注解开启二级缓存
哪个IDao接口需要就写在哪儿;写在接口上面;
@CacheNamespace(blocking = true)

本文详细介绍MyBatis注解的使用方法,包括基本的CRUD操作、复杂查询及二级缓存配置等高级特性。通过具体示例展示了如何在接口方法上应用注解来替代XML配置文件。
1820

被折叠的 条评论
为什么被折叠?



