Mybatis学习04:使用注解进行Mybatis开发

Mybatis支持使用注解实现DAO层接口,但是Mybatis主配置文件SqlMapConfig.xml不能用注解替代.

使用注解后,Mybatis就不支持xml配置了,若对应目录下存在xml实现DAO接口的配置,则会报错

使用注解配置CRUD

在DAO层接口方法的定义上添加@Insert,@Update,@Delete,@Select注解可以实现CRUD,其value属性的值为对应的sql语句.示例如下:

package cn.maoritian.dao;

public interface IUserDao {

    // 查询所有用户
    @Select("select * from users")
    List<User> findAllUsers();

    // 保存用户
    @Insert("insert into users(username,address,sex,birthday) values(#{username},#{address},#{sex},#{birthday})")
    void saveUser(User user);

    // 更新用户
    @Update("update users set username=#{username},sex=#{sex},birthday=#{birthday},address=#{address} where id=#{id}")
    void updateUser(User user);

    // 删除用户
    @Delete("delete from users where id=#{id} ")
    void deleteUser(Integer userId);

    // 根据id查询用户
    @Select("select * from users where id=#{id} ")
    User findById(Integer userId);

    // 根据用户名称模糊查询
    @Select("select * from users where username like '%${value}%' ")
    List<User> findUserByName(String username);

    // 查询总用户数量
    @Select("select count(*) from users ")
    int findTotalUser();
}

使用注解配置多表查询和延迟加载

配置输出参数映射的注解如下:

@Results注解用于配置输出参数映射,其属性如下:

  • id: 映射规则的唯一id,可以通过接口方法的@ResultMap注解引用.

  • values: 存储@Result注解集合,配置每一个字段的映射规则.

@Result注解用于配置单个字段的映射规则,其属性如下:

  • id: 表示当前字段是否为主键字段,默认值false.
  • column: 数据库列名.
  • property: pojo类属性名.
  • one: 使用@One注解引用其它pojo对象.
  • many: 使用@Many注解引用其它pojo对象集合.

@One@Many注解用来引用其它pojo对象或pojo对象集合,其属性如下:

  • select: 副查询方法的全类名.使用外层@Resultcolumn属性作为参数
  • fetchType: 加载模式,可选值:FetchType.LAZY表示延迟加载,FetchType.EAGER表示立即加载.

示例如下:

package cn.maoritian.dao;

public interface IUserDao {

 	// 查询所有用户及其对应的帐户信息
	@Select("select * from users")
    @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 = "cn.maoritian.dao.IAccountDao.findAccountByUid", fetchType = FetchType.LAZY)
            )
    })
    List<User> findAll();
}
package cn.maoritian.dao;

public interface IAccountDao {

    // 查询所有账户及其对应的用户信息
    @Select("select * from accounts")
    @Results(id = "accountMap", value = {
            @Result(id = true, column = "id", property = "id"),
            @Result(column = "uid", property = "uid"),
            @Result(column = "money", property = "money"),
            @Result(property = "user", column = "uid", 
                    one = @One(select = "cn.maoritian.dao.IUserDao.findById", fetchType = FetchType.EAGER)
            )
    })
    List<Account> findAll();
}

使用注解配置缓存

Mybatis的缓存分为一级缓存二级缓存,其中一级缓存在同一个SqlSession对象内共享,二级缓存在所有操作同一个Mapper(即DAO层接口)的SqlSession间共享.
在这里插入图片描述

  • 一级缓存是默认开启的,当调用SqlSession修改,添加,删除,commit(),close()方法时会清空一级缓存,也可以显式调用SqlSession对象的clearCache()方法清空缓存.

  • 二级缓存默认是关闭的,可以通过Mybatis主配置文件SqlMapConfig.xml<settings>标签下配置开启二级缓存.

    <settings>
        <!-- 开启Mybatis二级缓存 -->
        <setting name="cacheEnabled" value="true"/>
    </settings>
    

    在Mapper对象(即DAO层接口)的定义上加上@CacheNamespace(blocking=true)注解可以使访问此Mapper的所有SqlSession对象共享二级缓存.

    package cn.maoritian.dao;
    
    @CacheNamespace(blocking=true)	// 访问此Mapper对象的SqlSession共享二级缓存
    public interface IUserDao {
        
    	// DAO层方法...
    }
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值