Mybatis >注解开发,MySQL一对一接口注解配置,一对多接口注解配置,开启懒加载

Account实体类

在这里插入图片描述

User实体类

在这里插入图片描述

》一对一 接口注解配置

>> public interface IAccountDao

	// 查询所有
	// Select注解内为查询所需要的语句
    @Select("select * from account")
    // Results 内为查询所需要的属性和mysql字段的对应关系
    @Results(value = {
    
    
    		// id = true:表示该字段为主键字段 property表示实体类中的属性,column表示mysql中的字段名称
            @Result(id = true , property = "id" , column = "id"),
            @Result(property = "uid" , column = "uid"),
            @Result(property = "money" , column = "money"),
            // user表示 Account实体类中有一个User的引用类,用来封装账户所对应的用户对象
            @Result(property = "user" , column = "uid" ,
            // javaType 表示返回值对应的类型为User引用类型
            javaType = User.class ,
            // one表示这是一对一的情况,一个账户也只会返回一个对应的用户,因此用one
            // one属性对应xml配置中的association标签 select为查询后续所需数据用到的方法来自于哪个接口
            one = @One(select = "com.xx.dao.IUserDao.findByIdUser" , 
            // 获取值的方式采用立即加载
            fetchType = FetchType.EAGER))
    })
    List<Account> findAll_01();

>> public interface IUserDao

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

>> 测试接口 findAll_01()

在这里插入图片描述
测试成功,一对一实现完成,一个账户对应一个用户

》一对多 接口注解配置

>> public interface IUserDao

	@Select("select * from user")
    @Results(id = "userMapper" , value = {
    
    
            @Result(id = true, column = "id",property = "id"),
            @Result(column = "username",property = "username"),
            @Result(column = "birthday",property = "birthday"),
            @Result(column = "address",property = "address"),
            @Result(column = "gender",property = "gender"),
            @Result(property = "accounts" ,column = "id" , 
            // 由于是一对多,一个用户对应多个账户,类似一张身份证可以办理多张银行卡,因此使用的属性为many,
            // select属性对应根据uid查询其账户,方法名称为接口下的某个方法
            many = @Many(select = "com.xx.dao.IAccountDao.findAllByUID" , 
            // 获取方式采用懒加载,需要在mybatis的配置文件中开启懒加载
            fetchType = FetchType.LAZY))
    })
    // IUserDao 接口中的一个方法
    List<User> findAll();

>> public interface IAccountDao

	// 根据UID查询账户
    @Select("select * from account where uid = #{id}")
    List<Account> findAllByUID(Integer uid);

>> 测试接口中方法 > findAll()

在这里插入图片描述
测试完成 End

猜你喜欢

转载自blog.csdn.net/weixin_43309893/article/details/119464772