欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

MyBatis一对多实现延迟加载

程序员文章站 2022-07-12 22:23:01
...

数据库表
MyBatis一对多实现延迟加载
添加外键
MyBatis一对多实现延迟加载
在IDEA中创建maven项目

整体架构

MyBatis一对多实现延迟加载

pom.xml

<?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.uek</groupId>
    <artifactId>mybatis04-study01-oneTomeny-lazyLoad</artifactId>
    <version>1.0-SNAPSHOT</version>


    <!--打包方式-->
    <packaging>jar</packaging>

    <dependencies>
        <!--导入MyBatis的坐标-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>
        <!--导入MySQL-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.46</version>
        </dependency>

        <!--日志-->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

        <!--单元测试-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
        </dependency>

    </dependencies>
</project>

MyBatis的主配置文件

在resource目录下------SqlMapConfig.xml

<?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>

    <!--配置参数-->
    <settings>
        <!--开启MyBatis支持延迟加载-->
        <setting name="lazyLoadingEnabled" value="true"/>
        <setting name="aggressiveLazyLoading" value="false"/>
    </settings>

    <!--使用typeAliases配置别名,它只能配置到domian中类的别名-->
    <typeAliases>
        <package name="com.uek.domian"/>
    </typeAliases>
    
    <!--配置环境-->
    <environments default="mysql">
        <!--配置mysql的环境-->
        <environment id="mysql">
            <!--配置事务-->
            <transactionManager type="JDBC"></transactionManager>
            <!--配置连接池-->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=false"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <!--配置映射文件的位置-->
    <mappers>
        <package name="com.uek.dao"/>
    </mappers>
</configuration>

实体类

public class Account implements Serializable {

    private Integer id;
    private Integer uid;
    private Double money;
    
    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;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", uid=" + uid +
                ", money=" + money +
                '}';
    }
}

public class User implements Serializable {

    private Integer id;
    private String username;
    private String address;
    private String sex;
    private Date birthday;

    private Account accounts;

    public String getUsername() {
        return username;
    }

    public Account getAccounts() {
        return accounts;
    }

    public void setAccounts(Account accounts) {
        this.accounts = accounts;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername(String mybatis_saveuser) {
        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;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", address='" + address + '\'' +
                ", sex='" + sex + '\'' +
                ", birthday=" + birthday +
                '}';
    }
}

dao层接口

public interface IAccountDao {

    //第一种方法
    //查询所有账户,并且带有用户名称和地址信息
    List<Account> findAll();

    //根据用户id查询账户信息
    List<Account> findAccountById(Integer uId);

}
public interface IUserDao {

    //查询所有用户
    List<User> findAll();

    //根据id查询用户信息
    User findById(Integer userId);


接口配置 IUserDao.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.uek.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" select="com.uek.dao.IAccountDao.findAccountById" column="id">

        </collection>
    </resultMap>

    <!--查询所有方法-->
    <select id="findAll" resultMap="userAccountMap">
        select * from user
    </select>

    <!--根据id查询用户-->
    <select id="findById" parameterType="INT" resultType="user">
        select * from user where id = #{uid}
    </select>


</mapper>

接口配置 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="com.uek.dao.IAccountDao">
    <!--定义封装account和user的resultMap-->
    <resultMap id="accountUserMap" type="account">
        <!--account的数据封装完成   aid是sql语句中起的别名-->
        <id property="id" column="id"></id>
        <result property="uid" column="uid"></result>
        <result property="money" column="money"></result>
    </resultMap>

    <!--查询所有账户-->
    <select id="findAll" resultMap="accountUserMap">
        select * from account
    </select>

    <!--根据用户id查询账户信息-->
    <select id="findAccountById" resultType="account">
        select * from account where uid = #{uid}
    </select>
</mapper>

测试类

public class UserTest {

    private InputStream in;
    private SqlSession sqlSession;
    private IUserDao userDao;

    @Before   //用于在测试方法执行之前执行
    public void init() throws Exception {
        //1.读取配置文件,生成字节输入流
        in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //2.获取SqlSession对象
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        //3.获取SqlSession对象
        sqlSession = factory.openSession();
        //4.获取dao的代理对象
        userDao = sqlSession.getMapper(IUserDao.class);
    }


    @After //用于在测试方法执行之后执行
    public void destroy() throws Exception {
        //提交事务
        sqlSession.commit();

        //6.释放资源
        sqlSession.close();
        in.close();
    }

    //测试:查询所有
    @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());
        }
    }


    //测试:查询一个操作
    @Test
    public void testSelectOne(){
        //执行查询一个方法
        User byId = userDao.findById(8);
        System.out.println(byId);
    }
}

相关标签: MyBatis mybatis

上一篇: MyBatis——缓存

下一篇: mybatis 缓存