MyBatis注解查询 一对一、一对多

学习笔记

Mybatis 注解查询

*实体类*

// 用户实体
@Data
public class Users {
	Integer nId;
	String name;
	int age;
	Houses house;
	List<Animal> animal;
}

// 房子实体
@Data
public class Houses {
	Integer nId;
	String address;
}

// 宠物实体
@Data
public class Animal {
	Integet nid;
	String name;
}


数据库

用户表
users(
	id int,
	name varchar(64),
	nage int,
	houseId int,
)

房子表
house(
	id int,
	address varchar(255)
)

宠物表
animal(
	id int,
	name varchar(64),
	director int
)


一对一查询

@Mapper // 如果在启动类上添加了@MapperScan() 可以省略
@Repository
public interface EssayDao {
	@Select("select * from users")
    @Results({
    		// 处理属性名和数据表列名不一致问题,属性名为 "property",列名为 "column"
            @Result(property = "age", column = "nage"),
            // 如果只需要房子名称而不需要房子对象,可以将 "hourse" 的类型修改为 "String",此时需要 "one" 调用方法的返回结果也为 "String"。
            // 查询用户对应的房子,其中, "property" 的类型 和 "one" 返回的类型需要一致,"column" 的内容为传递给 "one" 调用方法的参数,该参数需要是数据库的列名
            @Result(property = "house", column = "houseId", one = @One(select = "cn.springboot.test.Dao.EssayDao.selectHouseById"))
    })
    List<EssayBean> selectAllEssay();

	@Select("Select * from house where id = #{id}")
	Houses selectHouseById(@Param("id") int id);
}

一对多查询

@Mapper // 如果在启动类上添加了@MapperScan() 可以省略
@Repository
public interface EssayDao {
	@Select("select * from users")
    @Results({
    		// 处理属性名和数据表列名不一致问题,属性名为 "property",列名为 "column"
            @Result(property = "age", column = "nage"),
            // 查询用户拥有的宠物,其中, "property" 的类型 和 "one" 返回的类型需要一致,"column" 的内容为传递给 "one" 调用方法的参数,该参数需要是数据库的列名
            @Result(property = "animal", column = "id", one = @One(select = "cn.springboot.test.Dao.EssayDao.selectAnimalById"))
    })
    List<EssayBean> selectAllEssay();

	@Select("Select * from animal where director = #{id}")
	List<Animal> selectAnimalById(@Param("id") int id);
}

对于数据库类名和属性名存在不一致问题,可以使用 @Result 声明不一致的,一致的可以不用写,注解查询比使用XML方法方便多了。

如果有问题请指正。

参考文档:https://www.cnblogs.com/a8457013/p/9074930.html
官方@Result介绍:http://localhost:63342/graduatation3/mybatis-3.5.6-javadoc.jar/org/apache/ibatis/annotations/Result.html?_ijt=pu6iikguemnnphq3mtk0mbmf94

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值