一、概述
1、延遲加載:
- 就是在需要用到數據時才進行加載,不需要用到數據時就不加載數據。延遲加載也稱懶加載
2、好處:
- 先從單表查詢,需要時再從關聯表去關聯查詢,大大提高數據庫性能,因爲查詢單表要比關聯查詢多張錶速度要快。
3、壞處:
- 因爲只有當需要用到數據時,纔會進行數據庫查詢,這樣在大批量數據查詢時,因爲查詢工作也要消耗時間,所以可能造成用戶等待時間變長,造成用戶體驗下降。
4、MyBatis 多表查詢
具體查詢步驟請 點擊
在多表查詢時,使用了resultMap
來實現一對一,一對多,多對多關係的操作。主要是通過 association
、collection
實現一對一及一對多映射。association
、collection
具備延遲加載功能。
二、association 延遲加載、collection 延遲加載
association : 用於一對多(一個用戶對應多個賬號:User ——> Account)
collection :用於多對一
第一步:封裝對數據庫映射的實體類 User.java、Account.java
package cn.lemon.domain;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class User implements Serializable {
private Integer id;
private Date birthday;
private String username;
private String sex;
private String address;
private List<Account> accountList = new ArrayList<>();
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
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 String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public List<Account> getAccountList() {
return accountList;
}
public void setAccountList(List<Account> accountList) {
this.accountList = accountList;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", birthday=" + birthday +
", username='" + username + '\'' +
", sex='" + sex + '\'' +
", address='" + address + '\'' +
'}';
}
}
package cn.lemon.domain;
import java.io.Serializable;
public class Account implements Serializable {
private Integer id;
private Integer uid;
private Double money;
private User user;//關聯屬性,記錄關聯關係
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
public Double getMoney() {
return money;
}
public void setMoney(Double money) {
this.money = money;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
@Override
public String toString() {
return "Account{" +
"id=" + id +
", uid=" + uid +
", money=" + money +
'}';
}
}
第二步:新建持久層(dao)接口 IUserDao.java 、IAccountDao.java,操作數據庫
package cn.lemon.dao;
import cn.lemon.domain.User;
import java.util.List;
public interface IUserDao {
public User findById(Integer userId);
public List<User> findAll();
}
package cn.lemon.dao;
import cn.lemon.domain.Account;
import java.util.List;
public interface IAccountDao {
public List<Account> findAll();
}
第三步:新建配置文件 SqlMapConfig.xml (配置懶加載)和 jdbcConfig.properties
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--mybatis配置文件-->
<configuration>
<!--配置屬性或使用屬性文件-->
<properties resource="jdbc.properties"/>
<!--全局屬性配置-->
<settings>
<!--開啓Mybatis支持延遲加載-->
<setting name="lazyLoadingEnabled" value="true"/>
<!--關閉積極延遲加載:任何屬性都會引起延遲加載-->
<setting name="aggressiveLazyLoading" value="false"></setting>
</settings>
<!--給包定義別名-->
<typeAliases>
<!--定義單個別名-->
<!--<typeAlias type="com.lxs.domain.User" alias="user"></typeAlias>-->
<!--配置包定義別名,別名=包中的類的名字(首字母大寫小寫都可以)-->
<package name="cn.lemon.domain"/>
</typeAliases>
<!--配置環境-->
<environments default="mysql">
<environment id="mysql">
<!--事務類型-->
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<!--配置連接池(數據源)-->
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<!--配置映射文件-->
<mappers>
<!--配置單個映射文件-->
<!--<mapper resource="com/lxs/dao/IUserDao.xml"></mapper>-->
<package name="cn.lemon.dao"/>
</mappers>
</configuration>
driver=com.mysql.jdbc.Driver
url=jdbc:mysql:///db_mybatis
username=root
password=lemon
第四步:編寫持久層接口的映射文件 IUserDao.xml、IAccountDao.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.lemon.dao.IUserDao">
<select id="findById" resultType="user" parameterType="int">
SELECT * FROM user WHERE id = #{uid}
</select>
<select id="findAll" resultMap="userMap">
SELECT * FROM user
</select>
<resultMap id="userMap" type="user">
<id column="id" property="id"></id>
<!--collection:映射一對多的一的一方(主表方)的集合屬性
ofType:集合的元素類型,可以寫別名
select: 查詢關聯集合的select語句
column:查詢關聯集合的語句的參數
-->
<collection property="accountList" ofType="Account" select="cn.lemon.dao.IAccountDao.findByUid" column="id">
<id column="id" property="id"/>
</collection>
</resultMap>
</mapper>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.lemon.dao.IAccountDao">
<select id="findAll" resultMap="accountMap">
select * from account
</select>
<resultMap id="accountMap" type="account">
<id column="id" property="id"/><!--字段名等於屬性名可以省略-->
<result column="uid" property="uid"/>
<!--<result property="money" column="money"></result>-->
<!--association映射多對一,多的一方的實體屬性
* select: 調用select映射的語句查詢關聯的user數據
* column: 調用select映射的語句的輸入參數
-->
<association property="user" javaType="user" select="cn.lemon.dao.IUserDao.findById" column="uid">
<!--主鍵不能省略-->
<id column="id" property="id"/>
<!-- 同名屬性可以省略 -->
<result property="username" column="username"/>
<!--<result property="birthday" column="birthday"></result>-->
<!--<result property="sex" column="sex"></result>-->
<!--<result property="address" column="address"></result>-->
</association>
</resultMap>
<select id="findByUid" resultType="Account" parameterType="int">
SELECT * FROM account WHERE uid= #{aid}
</select>
</mapper>
第五步:測試類
package cn.lemon.dao;
import cn.lemon.domain.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.InputStream;
import java.util.List;
public class IUserDaoTest {
private InputStream inputStream;
private SqlSessionFactory sqlSessionFactory;
private SqlSession sqlSession;
private IUserDao iUserDao;
@Before
public void init() throws Exception {
inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
sqlSession = sqlSessionFactory.openSession(true);
iUserDao = sqlSession.getMapper(IUserDao.class);
}
@Test
public void findById() {
}
@Test
public void findAll() {
List<User> userList = iUserDao.findAll();
for (User user : userList) {
System.out.println(user);
System.out.println("====================================================================");
}
System.out.println("-------------------------------------------------------------------------");
System.out.println("第一個用戶的賬戶" + userList.get(0).getAccountList());
}
@After
public void destory() throws Exception {
sqlSession.close();
inputStream.close();
}
}
package cn.lemon.dao;
import cn.lemon.domain.Account;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.InputStream;
import java.util.List;
import static org.junit.Assert.*;
public class IAccountDaoTest {
private InputStream inputStream;
private SqlSessionFactory sqlSessionFactory;
private SqlSession sqlSession;
private IAccountDao iAccountDao;
@Before
public void init() throws Exception {
inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
sqlSession = sqlSessionFactory.openSession(true);
iAccountDao = sqlSession.getMapper(IAccountDao.class);
}
@Test
public void findAll() {
List<Account> accountList = iAccountDao.findAll();
for (Account account : accountList) {
System.out.println(account);
System.out.println("--------------------------------------------------------------------------------");
}
System.out.println("***************************************************************************");
System.out.println("第一個賬戶的用戶爲:" + accountList.get(0).getUser());//當使用用戶時才查詢用戶,稱爲懶加載
}
@After
public void destory() throws Exception {
sqlSession.close();
inputStream.close();
}
}