Mybatis入门笔记(14)——基于注解开发一对多的查询配置
需求:使用注解方式实现,查询用户信息时,也要查询对应的账户列表。
一个用户具有多个账户信息,所以形成了用户(User)与账户(Account)之间的一对多关系。
-
User实体类中加入
List<Account>
package com.ben.domain; import java.io.Serializable; import java.util.Date; import java.util.List; /** * @ClassName: User * @author: benjamin * @version: 1.0 * @description: TODO * @createTime: 2019/07/19/21:43 */ public class User implements Serializable { private int id; private String username;// 用户姓名 private String sex;// 性别 private Date birthday;// 生日 private String address;// 地址 //一对多关系映射:主表方法应该包含一个从表方的集合引用。 private List<Account> accounts; public List<Account> getAccounts() { return accounts; } public void setAccounts(List<Account> accounts) { this.accounts = accounts; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "User [id=" + id + ", username=" + username + ", sex=" + sex + ", birthday=" + birthday + ", address=" + address + "]"; } }
-
编写用户的持久层接口并使用注解配置
/** * @Description: 查询所有用户 * @Param: * @return: * @Author: benjamin * @Date: 2019/7/19 */ @Select("select * from user") @Results(id="userMap", value = { @Result(id=true,column = "id",property = "id"), @Result(column = "username", property = "username"), @Result(column = "sex", property = "sex"), @Result(column = "address", property = "address"), @Result(column = "birthday", property = "birthday"), @Result(column = "id", property = "accounts", many = @Many( select = "com.ben.dao.IAccountDao.findAccountById", fetchType = FetchType.LAZY ) ) }) List<User> findAll();
-
编写账户的持久层接口并使用注解配置
/** * @Description: 根据用户ID查询用户下的所有账户 * @Param: * @return: * @Author: benjamin * @Date: 2019/7/20 */ @Select("select * from account where uid = #{id}") List<Account> findAccountByID(Integer userId);
-
编写测试方法
//测试查询所有 @Test public void testFindAll(){ List<User> users = userDao.findAll(); for(User user : users){ System.out.println("----每个用户拥有不止一个账户----"); System.out.println(user); System.out.println(user.getAccounts()); } }