mybatis-1对1-lazy
account与user是一对一的关系
1.pom
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.lq</groupId><artifactId>mybatis-one-lazy</artifactId><version>1.0-SNAPSHOT</version><packaging>jar</packaging><dependencies><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.4.5</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.6</version></dependency><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.12</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.10</version></dependency></dependencies></project>
2.IAccountDao
package com.lq.dao;import com.lq.domain.Account;import java.util.List;public interface IAccountDao {
List<Account> findAll();}
3.IUserDao
package com.lq.dao;import com.lq.domain.User;import java.util.List;public interface IUserDao {
List<User> findAll();User findById(Integer userId);}
4.Account
package com.lq.domain;import java.io.Serializable;public class Account implements Serializable {
private Integer id;private Integer uid;private Double money;//从表实体应该包含一个主表实体的对象引用private User user;public User getUser() {
return user;}public void setUser(User user) {
this.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;}@Overridepublic String toString() {
return "Account{" +"id=" + id +", uid=" + uid +", money=" + money +'}';}
}
5.User
package com.lq.domain;import java.io.Serializable;
import java.util.Date;
import java.util.List;public class User implements Serializable {
private Integer id;private String username;private String address;private String sex;private Date birthday;//一对多关系映射:主表实体应该包含从表实体的集合引用private List<Account> accounts;public List<Account> getAccounts() {
return accounts;}public void setAccounts(List<Account> 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 String getAddress() {
return address;}public void setAddress(String address) {
this.address = address;}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;}@Overridepublic String toString() {
return "User{" +"id=" + id +", username='" + username + '\'' +", address='" + address + '\'' +", sex='" + sex + '\'' +", birthday=" + birthday +'}';}
}
6.IAccountDao.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lq.dao.IAccountDao"><!-- 定义封装account和user的resultMap --><resultMap id="accountUserMap" type="account"><id property="id" column="id"></id><result property="uid" column="uid"></result><result property="money" column="money"></result><!-- 一对一的关系映射:配置封装user的内容select:根据uid查询用户user信息column:根据id查询时的参数--><association property="user" column="uid" javaType="user" select="com.lq.dao.IUserDao.findById"></association></resultMap><!-- 查询所有 --><select id="findAll" resultMap="accountUserMap">select * from account</select></mapper>
7.IUserDao.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lq.dao.IUserDao"><!-- 定义User的resultMap--><resultMap id="userAccountMap" type="user"><id property="id" column="id"></id><result property="username" column="username"></result><result property="address" column="address"></result><result property="sex" column="sex"></result><result property="birthday" column="birthday"></result><!-- 配置user对象中accounts集合的映射 --><collection property="accounts" ofType="account"><id column="aid" property="id"></id><result column="uid" property="uid"></result><result column="money" property="money"></result></collection></resultMap><!-- 查询所有 --><select id="findAll" resultMap="userAccountMap">select * from user u left outer join account a on u.id = a.uid</select><!-- 根据id查询用户 --><select id="findById" parameterType="INT" resultType="user">select * from user where id = #{
uid}</select></mapper>
8.jdbcConfig.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/eesy
jdbc.username=root
jdbc.password=root
9.log4j.properties
# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE debug info warn error fatal
log4j.rootCategory=debug, CONSOLE, LOGFILE# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{
ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=d:\axis.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{
ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
10.SqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><!-- 配置properties--><properties resource="jdbcConfig.properties"></properties><!--设置懒加载--><settings><setting name="lazyLoadingEnabled" value="true"/><setting name="aggressiveLazyLoading" value="false"/></settings><!--使用typeAliases配置别名,它只能配置domain中类的别名 --><typeAliases><package name="com.lq.domain"></package></typeAliases><!--配置环境--><environments default="mysql"><!-- 配置mysql的环境--><environment id="mysql"><!-- 配置事务 --><transactionManager type="JDBC"></transactionManager><!--配置连接池--><dataSource type="POOLED"><property name="driver" value="${jdbc.driver}"></property><property name="url" value="${jdbc.url}"></property><property name="username" value="${jdbc.username}"></property><property name="password" value="${jdbc.password}"></property></dataSource></environment></environments><!-- 配置映射文件的位置 --><mappers><package name="com.lq.dao"></package></mappers>
</configuration>
11.AccountTest
package com.lq.test;import com.lq.dao.IAccountDao;
import com.lq.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;public class AccountTest {
private InputStream in;private SqlSession sqlSession;private IAccountDao accountDao;@Before//用于在测试方法执行之前执行public void init()throws Exception{
//1.读取配置文件,生成字节输入流in = Resources.getResourceAsStream("SqlMapConfig.xml");//2.获取SqlSessionFactorySqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);//3.获取SqlSession对象sqlSession = factory.openSession(true);//4.获取dao的代理对象accountDao = sqlSession.getMapper(IAccountDao.class);}@After//用于在测试方法执行之后执行public void destroy()throws Exception{
//提交事务// sqlSession.commit();//6.释放资源sqlSession.close();in.close();}/*** 测试查询所有*/@Testpublic void testFindAll(){
List<Account> accounts = accountDao.findAll();for(Account account : accounts){
System.out.println("--------每个account的信息------------");System.out.println(account);System.out.println(account.getUser());}}
}