vo 使用和懒加载demo
懒加载,顾名思义就是懒得加载的意思吧,我是这么理解的。
当我们有两个表需要关联查询的时候,Author(用户表),和blog(博客表)。首先实体类之间的关系肯定是一对一。
然后我们现在有一个需求:查询出博客title是XXX的用户信息。
可以很清楚的知道将会怎么查询:select * from blog,Author where blog.author_id=author.id and blog.title="XXX";
使用懒加载其实又是一次查询操作:
1-->select * from blog where title="XXX"
2-->select * from author where id=author_id;
懒加载查询需要传递一些参数,还有一些其他条件,当执行第一个sql 的时候,mybatis会为author生成动态代理对象,将所有需要的信息封装到内部。
下面是相关一些代码及配置:
创建表:
CREATE TABLE author
(
id INT NOT NULL,
username VARCHAR(10) NOT NULL,
PASSWORD VARCHAR(30) NOT NULL,
email VARCHAR(30),
bio VARCHAR(30)
);
INSERT INTO author(id,username,PASSWORD,email,bio)
VALUES(1,'user1','user1','[email protected]','guy');
INSERT INTO author(id,username,PASSWORD,email,bio)
VALUES(2,'user2','user2','[email protected]','guy');
INSERT INTO author(id,username,PASSWORD,email,bio)
VALUES(3,'user3','user3','[email protected]','guy');
INSERT INTO author(id,username,PASSWORD,email,bio)
VALUES(4,'user4','user4','[email protected]','guy');
INSERT INTO author(id,username,PASSWORD,email,bio)
VALUES(5,'user5','user5','[email protected]','guy');
INSERT INTO author(id,username,PASSWORD,email,bio)
VALUES(6,'user6','user6','[email protected]','guy');
CREATE TABLE blog
(
id INT NOT NULL PRIMARY KEY,
title VARCHAR(30) DEFAULT 'My Blog',
author_id INT NOT NULL
);
INSERT INTO blog(id,title,author_id) VALUES(1,'just fun',1);
INSERT INTO blog(id,title,author_id) VALUES(2,'just funny',2);
INSERT INTO blog(id,author_id) VALUES(3,3);
INSERT INTO blog(id,author_id) VALUES(4,4);
INSERT INTO blog(id,title,author_id) VALUES(5,'hello one',5);
INSERT INTO blog(id,title,author_id) VALUES(6,'hello two',6);
实体类 Author.java和 VoAuthor.java 编写 |
package com.task.entity;
publicclass Author { privateintid; private String username; private String password; private String email; private String bio; publicint getId() { returnid; } publicvoid setId(int id) { this.id = id; } public String getUsername() { returnusername; } publicvoid setUsername(String username) { this.username = username; } public String getPassword() { returnpassword; } publicvoid setPassword(String password) { this.password = password; } public String getEmail() { returnemail; } publicvoid setEmail(String email) { this.email = email; } public String getBio() { returnbio; } publicvoid setBio(String bio) { this.bio = bio; } }
|
package com.task.entity;
publicclass VoAuthor{ private Author author; private String title; //表blog 中的title
public String getTitle() { returntitle; }
publicvoid setTitle(String title) { this.title = title; }
public Author getAuthor() { returnauthor; }
publicvoid setAuthor(Author author) { this.author = author; }
@Override public String toString() { return"VoAuthor [author=" + author.getEmail() + ", title=" + title + "]"; } }
|
编写 dao 层接口 |
package com.task.dao;
import com.task.entity.VoAuthor;
publicinterface AuthorDao {
public VoAuthor getVoAuthor(VoAuthor author); }
|
Mapper.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="com.task.dao.AuthorDao">
<select id="getVoAuthor" parameterType="VoAuthor" resultMap="resultMap"> SELECT * FROM blog where title=#{title} </select>
<!-- association:处理一对一关系 property:和实体类属性名对应 javaType:指定类型 column:指定查询条件 selectid:指定要执行的SQL fetchType:懒加载 --> <resultMap type="com.task.entity.VoAuthor" id="resultMap"> <association property="author" javaType="com.task.entity.Author" column="id" select="selectAuthor" fetchType="lazy"/> </resultMap> <select id="selectAuthor" parameterType="int" resultType="com.task.entity.Author"> select * from author where id=#{id}
</select> </mapper>
|
Mapper配置文件 |
<?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"> <configuration> <properties resource="jdbc.properties"></properties>
<settings> <setting name="lazyLocationEnabled" value="true"/> 将积极加载改为消极加载,即按需加载 <setting name="aggressiveLazyLoading" value="false"/> </settings> <typeAliases> <typeAlias type="com.task.entity.VoAuthor" alias="VoAuthor"/>
</typeAliases>
<environments default="development"> <environment id="development"> <transactionManager type="JDBC"></transactionManager> <dataSource type="POOLED"> <property name="driver" value="${mysql.driver}"/> <property name="url" value="${mysql.url}"/> <property name="username" value="${mysql.username}"/> <property name="password" value="${mysql.password}"/> </dataSource> </environment>
</environments> <mappers> <mapper resource="com/task/mapper/Authormapper.xml"/>
</mappers> </configuration>
|
Jdbc.properties 属性文件 |
mysql.driver=com.mysql.jdbc.Driver mysql.url=jdbc:mysql://127.0.0.1:3306/test mysql.username=root mysql.password=123456
|
Log4j.properties属性文件 |
log4j.rootLogger=debug,c1
log4j.appender.c1=org.apache.log4j.ConsoleAppender log4j.appender.c1.layout=org.apache.log4j.PatternLayout
|
测试类编写 |
package com.task.tests;
import java.io.IOException; import java.io.Reader;
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 com.task.dao.AuthorDao; import com.task.entity.VoAuthor;
publicclass Tests {
publicstaticvoid main(String[] args) {
try { Reader context=Resources.getResourceAsReader("config.xml"); SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(context); SqlSession session=factory.openSession(); AuthorDao authorDao=session.getMapper(AuthorDao.class); VoAuthor author=new VoAuthor(); author.setTitle("just fun"); //只执行第一句SQL VoAuthor voAuthor=authorDao.getVoAuthor(author); //调用voAuthor类中toString时,会调用author.getEmail() ;这个时候执行第二句SQL System.out.println(voAuthor.toString()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }
} }
|
结果: |
Setting autocommit to false on JDBC Connection [[email protected]] ==> Preparing: SELECT * FROM blog where title=? ==> Parameters: just fun(String) <== Total: 1 ==> Preparing: select * from author where id=? ==> Parameters: 1(Integer) <== Total: 1 VoAuthor [[email protected], title=just fun] |