学习建设网站,新手学网站建设解疑与技巧1200例,移动建站公司,梵客家装电话MyBatis的延迟加载#xff08;一对多查询案例#xff09;
1.什么是延迟加载#xff1f;
开启延迟加载后#xff0c;在真正使用数据的时候才发起级联查询#xff0c;不用的时候不查询。
2.pojo
User类#xff1a;
package com.wt.pojo;import java.io.Serializable;
…MyBatis的延迟加载一对多查询案例
1.什么是延迟加载
开启延迟加载后在真正使用数据的时候才发起级联查询不用的时候不查询。
2.pojo
User类
package com.wt.pojo;import java.io.Serializable;
import java.util.Date;
import java.util.List;public class User implements Serializable {private Integer id;private String username;private Date birthday;private String sex;private String address;//加入ListAccount存储用户所拥有的账户private ListAccount accounts;public ListAccount getAccounts() {return accounts;}public void setAccounts(ListAccount accounts) {this.accounts accounts;}public Integer getId() {return id;}public void setId(Integer id) {this.id id;}public String getUsername() {return username;}public void setUsername(String username) {this.username username;}public Date getBirthday() {return birthday;}public void setBirthday(Date birthday) {this.birthday birthday;}public String getSex() {return sex;}public void setSex(String sex) {this.sex sex;}public String getAddress() {return address;}public void setAddress(String address) {this.address address;}Overridepublic String toString() {return User{ id id , username username \ , birthday birthday , sex sex \ , address address \ , accounts accounts };}
}Account类略
3.mapper
UserDao:
public interface UserDao {public ListUser findAll();
}AccountDao:
public interface AccountDao {Account findAccountById(Integer id);
}
UserDao.xml:
?xml version1.0 encodingUTF-8?
!DOCTYPE mapperPUBLIC -//mybatis.org//DTD Mapper 3.0//ENhttp://mybatis.org/dtd/mybatis-3-mapper.dtd
mapper namespacecom.wt.dao.UserDaoresultMap typeUser idfindAllResultMapid columnid propertyid/idresult columnusername propertyusername/result columnaddress propertyaddress/result columnsex propertysex/result columnbirthday propertybirthday/!--property属性名ofType泛型select 要调用的 select 映射的 idcolumn 传递给 select 映射的参数fetchTypelazy懒加载默认情况下是没有开启延迟加载的--collection propertyaccounts ofTypeAccountselectcom.by.dao.AccountDao.findAccountById columnidfetchTypelazy /collection/resultMapselect idfindAll resultMapfindAllResultMapselect * from user/select
/mapperAccountDao.xml:
?xml version1.0 encodingUTF-8?
!DOCTYPE mapperPUBLIC -//mybatis.org//DTD Mapper 3.0//ENhttp://mybatis.org/dtd/mybatis-3-mapper.dtd
mapper namespacecom.wt.dao.AccountDaoselect idfindAccountById parameterTypeint resultTypeaccountselect * from account where uid #{id}/select
/mapper4.测试 Testpublic void testFindAll() {UserDao userDao sqlSession.getMapper(UserDao.class);ListUser userList userDao.findAll();for(User user : userList){System.out.println(user.getUsername());//不查询accountSystem.out.println(user.getAccounts());//查询account}}5.结果
不查询Account: 查询Account