学习笔记
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