使用注解开发一对多和开启二级缓存

简单的CRUD

public interface IUserDao {
/**
* 查询所有用户
* @return
*/
@Select("select * from user")
@Results(id="userMap",
value= {
@Result(id=true,column="id",property="userId"),
@Result(column="username",property="userName"),
@Result(column="sex",property="userSex"),
@Result(column="address",property="userAddress"),
@Result(column="birthday",property="userBirthday")
})
List<User> findAll();
/**
* 根据 id 查询一个用户
* @param userId
* @return
*/
@Select("select * from user where id = #{uid} ")
@ResultMap("userMap")
User findById(Integer userId);
/**
* 保存操作
* @param user,这里user存入之后user中有了id属性
* @return 影响行数
*/
@Insert("insert into 
user(username,sex,birthday,address)values(#{username},#{sex},#{birthday},#{address}
)")
//@Options(useGeneratedKeys = true , keyProperty = "id",keyColumn = "id"),这也可以让user有id属性
@SelectKey(keyColumn="id",keyProperty="id",resultType=Integer.class,before = 
false, statement = { "select last_insert_id()" })
int saveUser(User user);
/**
* 更新操作
* @param user
* @return
*/
@Update("update user set 
username=#{username},address=#{address},sex=#{sex},birthday=#{birthday} where id 
=#{id} ")
int updateUser(User user);
/**
* 删除用户
* @param userId
* @return
*/
@Delete("delete from user where id = #{uid} ")
int deleteUser(Integer userId);
/**
* 查询使用聚合函数
* @return
*/
@Select("select count(*) from user ")
int findTotal();
/**
* 模糊查询
* @param name
* @return
*/
@Select("select * from user where username like #{username} ")
List<User> findByName(String name);
}
//通过注解方式,我们就不需要再去编写 UserDao.xml 映射文件了

一对多查询

@CacheNamespace(blocking = true)
public interface IUserDao {
    /**
     * 返回查询所有
     * @return
     */
    @Select("select * from user")
    @Results(id="userMap",value = {
            @Result(id = true,property = "userId",column = "id"),
            @Result(property = "userName",column = "username"),
            @Result(property = "userSex",column = "sex"),
            @Result(property = "userBirthday",column = "birthday"),
            @Result(property = "userAddress",column = "address"),
            @Result(property = "accounts",column = "id",many = @Many(select = "cn.qut.dao.IAccountDao.findByUid",fetchType = FetchType.LAZY))
    })
    List<User> findAll();

    /**
     * 根据id返回用户
     * @return
     */
    @ResultMap("userMap")
    @Select("select * from where id=#{id}")
    User findById();
}

测试类:

在这里插入代码片

注释时的执行结果
准备了Preparing语句
执行了Preparing语句

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值