Mybatis学习笔记【part08】注解开发

导读:本篇文章讲解 Mybatis学习笔记【part08】注解开发,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

Mybatis 学习笔记 Part08

3. 注解开发

​ 这几年来注解开发越来越流行,Mybatis 也可以使用注解开发方式,这样我们就可以减少编写 Mapper 映射文件了。

常用注解说明
    @Insert:实现新增
    @Update:实现更新
    @Delete:实现删除
    @Select:实现查询
    @Result:实现结果集封装
    @Results:可以与@Result 一起使用,封装多个结果集
    @ResultMap:实现引用@Results 定义的封装
    @One:实现一对一结果集封装
    @Many:实现一对多结果集封装
    @SelectProvider: 实现动态 SQL 映射
    @CacheNamespace:实现注解二级缓存的使用

3.1 基本CURD实例

public interface IUserDao {
    
//基本
    //查
    @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();
    
    //增
    @Insert("insert into user(username,sex,birthday,address)values(#{username},#{sex},#{birthday},#{address})")
	@SelectKey(keyColumn="id",keyProperty="id",resultType=Integer.class,
               before = false, statement = { "select last_insert_id()" })
	int saveUser(User user);
    
    //删
	@Delete("delete from user where id = #{uid} ")
	int deleteUser(Integer userId);
    
    //改
    @Update("update user set username=#{username},address=#{address},sex=#{sex},birthday=#{birthday} where id =#{id} ")
	int updateUser(User user);
    
//拓展
    //单个主键查
    @Select("select * from user where id = #{uid} ")
	@ResultMap("userMap")
	User findById(Integer userId);
    
    //聚合函数
    @Select("select count(*) from user ")
	int findTotal();
    
    //模糊查询
    @Select("select * from user where username like #{username} ")
	List<User> findByName(String name);
}

​ 通过注解方式,我们就不需要再去编写 UserDao.xml 映射文件了。

3.2 SqlMapConfig配置package

<!-- 配置别名的注册 --> 
<typeAliases> 
    <package name="com.itheima.domain"/>
</typeAliases>

<!-- 配置映射信息 --> 
<mappers>
    <package name="com.itheima.mapper"/>
</mappers>

配置 mapper 接口的位置,注解开发有两种方式
第一种:使用 mapper 标签配置 class 属性
第二种:使用 package 标签,直接指定 mapper 接口所在的包
(第三种是resource属性,它只适用于xml开发,并且属性值格式为com/itheima/mapper/UserMapper.xml)

3.3 复杂关系映射开发

//@Results 注解
代替的是标签<resultMap>
    
可以使用单个@Result 注解:
    @Results@Result())
也可以使用@Result 集合:
    @Results{   @Result(),@Result(),@Result(),  ......    }
//@Resutl 注解
代替了 <id>标签和<result>标签
    
@Result 中 属性介绍:
    id 是否是主键字段
    column 数据库的列名
    property 需要装配的属性名
    one 需要使用的@One 注解
        @Result(one=@One())
    many 需要使用的@Many 注解
        @Result(many=@many())
//@One 注解(一对一)
代替了<assocation>标签,是多表查询的关键,在注解中用来指定子查询返回单一对象。
    
@One 注解属性介绍:
select 指定用来多表查询的 sqlmapper //select = "com.dao.UserMapper.findById"
fetchType 会覆盖全局的配置参数 lazyLoadingEnabled 。
    
使用格式:
@Result(column=" ",property="",one=@One(select=""))
//@Many 注解(多对一)
代替了<Collection>标签,是是多表查询的关键,在注解中用来指定子查询返回对象集合。
    
注意:聚集元素用来处理“一对多”的关系。
    需要指定映射的 Java 实体类的属性,属性的 javaType(一般为 ArrayList),但是注解中可以不定义。
    
使用格式:
@Result(property="",column="",many=@Many(select=""))

3.4 一对一实例

domain类
public class Account implements Serializable {
    
    private Integer id;
    private Integer uid;
    private Double money;
    //一对一关系映射:从表方应该包含一个主表方的对象引用
    private User user;
    
    /* getter + setter + toString */
}

dao类 
public interface IAccountDao {
    
    @Select("select * from account")
    @Results(id="accountMap",
        value= {
            @Result(id=true,column="id",property="id"),
            @Result(column="uid",property="uid"),
            @Result(column="money",property="money"),
            @Result(column="uid",
                    property="user",
                    one=@One(select="com.itheima.dao.IUserDao.findById",
                       		 fetchType=FetchType.LAZY) 
        )
    })
    List<Account> findAll();
}

(com.itheima.dao.IUserDao.findById) 夹带的dao类
public interface IUserDao {
    @Select("select * from user where id = #{uid} ")
    @ResultMap("userMap")
    User findById(Integer userId);
}

@One: 相当于的配置

select 属性:代表将要执行的 sql 语句

fetchType 属性:代表加载方式,一般如果要延迟加载都设置为 LAZY 的值

3.5 一对多实例

domain类
public class User implements Serializable {
    private Integer userId;
    private String userName;
    private Date userBirthday;
    private String userSex;
    private String userAddress;
    //一对多关系映射:主表方法应该包含一个从表方的集合引用
    private List<Account> accounts;
    
    /* getter + setter + toString */
}

dao类
public interface IUserDao {
    
    @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"),
            @Result(column="id",property="accounts",
                    many=@Many(
                            select="com.itheima.dao.IAccountDao.findByUid",
                            fetchType=FetchType.LAZY
                    )
              )
        })
    List<User> findAll();
}

com.itheima.dao.IAccountDao.findByUid(夹带的dao类)
public interface IAccountDao{
    @Select("select * from account where uid = #{uid} ")
	List<Account> findByUid(Integer userId);
}

@Many: 相当于的配置

select 属性:代表将要执行的 sql 语句

fetchType 属性:代表加载方式,一般如果要延迟加载都设置为 LAZY 的值

3.6 基于注解的二级缓存

第一步:

​ 在 SqlMapConfig 中开启二级缓存支持。

<!-- 配置二级缓存 --> 
<settings>
	<!-- 开启二级缓存的支持 --> 
    <setting name="cacheEnabled" value="true"/>
</settings>

第二步:

​ 在持久层接口中使用注解配置二级缓存。

@CacheNamespace(blocking=true)   //mybatis 基于注解方式实现配置二级缓存
public interface IUserDao {
    
}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由半码博客整理,本文链接:https://www.bmabk.com/index.php/post/84505.html

(0)

相关推荐

半码博客——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!