来源:黑马程序员
账户:
用户:
一对一
目标实现查找所有账户的同时找到对应的用户信息,立即加载
User属性:
private Integer id;
private String username;
private String address;
private String sex;
private Date birthday;
Account属性:
private Integer id;
private Integer uid;
private Double money;
//建立多对一关系(mybatis称之为1对1关系)
private User user;
User的dao层接口,根据user的id查找用户:
/**
* 根据ID查找用户
* @param id
* @return
*/
@Select("select * from user where id=#{id}")
User findByID(Integer id);
Account层实现查找所有账户的接口:
@Result(property = "user",column = "uid",one=@One( select="com.example.dao.IUserDao.findByID",fetchType = FetchType.EAGER)
property = "user" 实体类Account中的user属性,
column = "uid",用uid的字段查询对应的user信息,
one=@One( select="com.example.dao.IUserDao.findByID",fetchType = FetchType.EAGER),一对一关系, select内容是全限定类名加dao层的函数名,fetchType = FetchType.EAGER,为立即加载,还有懒加载FetchType.LAZY
/**
* 查询所有账户,并且获取所有账户下的用户信息
* @return
*/
@Select("select * from account")
@Results(id = "AccountMap",value = {
@Result(id=true,column = "uid",property = "uid"),
@Result(column = "id",property = "id"),
@Result(column = "money",property = "money"),
@Result(property = "user",column = "uid",one=@One( select="com.example.dao.IUserDao.findByID",fetchType = FetchType.EAGER))
})
List<Account> findAll();
一对多:
目标查找一个用户的所有账户:
配置User实体类,让他拥有List<Account>属性,并配置set,get方法
在Account的持久成接口中配置根据uid查找账户的功能
/**
* 根据用户uid查询所有的账户信息
* @param uid
* @return
*/
@Select("select * from account where uid = #{uid}")
@ResultMap("AccountMap")
List<Account> findByUid(Integer uid);
修改查询找所有用户的持久层接口
column="id"是指user的id,会传给many注解中的select指定的接口
many属性时一对多,one是一对一
/**
* 查找所有用户
* @return
*/
@Select(value = "select * from user")
@Results(id="UserMap",value = {
@Result(property = "accounts",column = "id",many =@Many(select = "com.example.dao.IAccountDao.findByUid",fetchType = FetchType.LAZY))
})
List<User> findAll();
测试类
@Test
public void testFindAll() throws IOException {
//执行dao方法
List<User> list = userDao.findAll();
for (User user:list){
System.out.println(user);
for (Account account :user.getAccounts()) {
System.out.println(account);
}
}
}