使用注解实现复杂关系映射开发

使用注解实现复杂关系映射开发

实现复杂关系映射之前我们可以在映射文件中通过配置来实现,在使用注解开发时我们需要借助@Results 注解,
@Result 注解,
@One 注解,
@Many 注解。
复杂关系映射的注解说明

@Results 注解

代替的是标签
该注解中可以使用单个@Result 注解,也可以使用@Result 集合
@Results({@Result(),@Result()})或@Results(@Result())

@Resutl 注解
代替了 标签和标签

@Result 中 属性介绍:

字段 描述
id 是否是主键字段
column 数据库的列名
property 需要装配的属性名
one 需要使用的@One 注解(@Result(one=@One)()))
many 需要使用的@Many 注解(@Result(many=@many)()))

@One 注解(一对一)
代替了标签,是多表查询的关键,在注解中用来指定子查询返回单一对象。

@One 注解属性介绍:

字段 描述
select 指定用来多表查询的 sqlMapper
fetchType 会覆盖全局的配置参数 lazyLoadingEnabled
FetchType.LAZY 延迟加载

使用格式:

@Result(column=" ",property="",one=@One(select=""),fetchType=FetchType.LAZY)

@Many 注解(多对一)
代替了标签,是是多表查询的关键,在注解中用来指定子查询返回对象集合。
注意:聚集元素用来处理“一对多”的关系。需要指定映射的 Java 实体类的属性,属性的 javaType(一般为 ArrayList)但是注解中可以不定义;
使用格式:

@Result(property="",column="",many=@Many(select=""))

使用注解实现一对一(多对一)复杂关系映射及延迟加载

需求:
加载账户信息时并且加载该账户的用户信息,根据情况可实现延迟加载。(注解方式实现)

  1. 添加 User 实体类及 Account 实体类
    在account类中加入User 属性

2.添加账户的持久层接口并使用注解配置

/**
     *
     * <p>Title: IAccountDao</p>
     * <p>Description: 账户的持久层接口</p>
     */
    public interface IAccountDao {
        /**
         * 查询所有账户,采用延迟加载的方式查询账户的所属用户
         *
         * @return
         */
        @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.lantian.dao.IUserDao.findById", FetchType = FetchType.LAZY))
                })
        List<Account> findAll();

    }
 

3.添加用户的持久层接口并使用注解配置

/**
     *
     * <p>Title: IUserDao</p>
     * <p>Description: 用户的持久层接口</p>
     */
    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);
    }
 
posted @ 2020-07-17 11:17  silence022  阅读(29)  评论(0)    收藏  举报