8.MyBatis中二表查询(一对多)

1.结构图

1.User实体类

package com.itheima.domain;

import java.io.Serializable;
import java.util.Date;

public class User implements Serializable {
    private Integer id;
    private String username;
    private Date birthday;
    private String sex;
    private String address;

    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;
    }

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

2.Account实体类

package com.itheima.domain;

public class Account {
    private String id;
    private String uid;
    private Double money;
    //从表实体应该包含一个主表实体的对象引用
    private User user;

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public String getId() {
        return id;
    }

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

    public String getUid() {
        return uid;
    }

    public void setUid(String 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 +
                ", user=" + user +
                '}';
    }
}

3.UserAccount实体类(重要)

package com.itheima.domain;

//继承Account
public class UserAccount extends Account {
    private String username;
    private String address;

    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;
    }
    /*继承父类的toString【super.toString()】*/
    @Override
    public String toString() {
        return super.toString()
                +"UserAccount{" +
                "username='" + username + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}

4.IUserDao接口

package com.itheima.dao;


import com.itheima.domain.User;

import java.util.List;

/*数据库操作接口:我们当然也可以通过实现类实现,但是mybatis环境帮我们配置了,所以我们不用写实现类*/
public interface IUserDao {
    //查询所有
    List<User> findAll();
    //查询一个
    User findUserById(Integer userId);
}

5.IAccountDao接口

package com.itheima.dao;

import com.itheima.domain.Account;
import com.itheima.domain.UserAccount;

import java.util.List;

public interface IAccountDao {
    /*查询所有*/
    List<Account> findAllAccount();
    /*两表联查
    * 查询用户的账户信息
    */
    List<UserAccount> findAllAccountUser();
}

6.IUserMapper对应接口映射文件

<?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.itheima.dao.IUserDao">
    <!--查询所有-->
    <select id="findAll" resultType="com.itheima.domain.User">
        select * from user
    </select>
    <!--查询一个通过id-->
    <select id="findUserById" parameterType="int" resultType="com.itheima.domain.User">
        select * from user where id=#{id}
    </select>
    <!--账户的查询-->
</mapper>

7.IAccountMapper对应接口映射文件

<?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.itheima.dao.IAccountDao">

    <!--将Account的信息和User的信息封装到ResultMap中去-->
    <resultMap id="userAccountMap" type="com.itheima.domain.Account">
        <id property="id" column="aid"></id>
        <result property="uid" column="uid"></result>
        <result property="money" column="money"></result>
        <!--一对一的关系映射:配置封装user的内容-->
        <!--association用来关联对象(用于多对一,或一对一),property代表加载对象,javaType代表加载对象的数据类型,可以写成com.cyannote.domain.User-->
        <association property="user" column="uid" javaType="com.itheima.domain.User">
            <id property="id" column="id"></id>
            <result column="username" property="username"></result>
            <result column="address" property="address"></result>
            <result column="sex" property="sex"></result>
            <result column="birthday" property="birthday"></result>
        </association>
    </resultMap>

    <!--封装的查询所有-->
    <select id="findAllAccount" resultMap="userAccountMap">
        <!--select u.*,a.id as aid,a.uid,a.money from account a,user u where u.id=a.uid-->
        select u.*,a.id as aid,a.uid,a.money from account a,user u where u.id = a.uid
    </select>

    <!--账户的查询所有-->
    <!--<select id="findAllAccount" resultType="com.itheima.domain.Account">
        select * from account
    </select>-->
    <!--
        查询所有账户同时包含 用户名 和 地址信息
    -->
    <select id="findAllAccountUser" resultType="com.itheima.domain.UserAccount">

        select a.*,u.username,u.address from account a,user u where u.id=a.uid
    </select>

</mapper>

8.外部数据库源jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db_mybatis
jdbc.username=root
jdbc.password=123456

9.主配置SqlMapConfig

<?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>
    <!--配置环境-->
    <environments default="mysql">
        <!--配置环境-->
        <environment id="mysql">
            <!--配置事务管理JDBC-->
            <transactionManager type="JDBC"></transactionManager>
            <!--POOLED-->
            <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>
    <!--IUserMapper.xml的配置-->
    <mappers>
        <mapper resource="com/itheima/dao/IUserMapper.xml"></mapper>
        <mapper resource="com/itheima/dao/IAccountMapper.xml"></mapper>
    </mappers>
</configuration>

10.测试类

package com.itheima;

import com.itheima.dao.IAccountDao;
import com.itheima.dao.IUserDao;
import com.itheima.domain.Account;
import com.itheima.domain.User;
import com.itheima.domain.UserAccount;
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.ArrayList;
import java.util.List;

public class MybatisCRUD {
    //为了不用重复使用
    private InputStream inputStream;
    private SqlSessionFactory factory;
    private SqlSession sqlSession;
    private IUserDao userDao;
    private IAccountDao accountDao;
    private UserAccount userAccount;
    /*初始化,在程序一运行的时候就准备好*/
    @Before
    public void  init() throws Exception{
        //1.获取配置文件SqlMapConfig的字节流
        inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
        //2.获取SqlSessionFactory,让builder创建factory
        factory = new SqlSessionFactoryBuilder().build(inputStream);
        //3.使用工厂创建session对象
        sqlSession = factory.openSession();
        //4.获取dao代理
        userDao = sqlSession.getMapper(IUserDao.class);
        //5.获取dao代理
        accountDao = sqlSession.getMapper(IAccountDao.class);
       /* //6.获取dao代理
        userAccount = sqlSession.getMapper(UserAccount.class);*/
    }
    //查询所有
    @Test
    public void findAlData(){
        //5.使用userDao调用执行该方法--返回一个结果集
        List<User> users = userDao.findAll();
        for (User user:users){
            System.out.println(user);
        }
    }
    //根据id查询一个用户信息
    @Test
    public void findUserByIdData(){
        User user = userDao.findUserById(1);
        System.out.println("查询id成功"+user);
    }


    /*
    * 账户的查询所有
    * */
    /*@Test
    public void testFindAllAccount(){
        List<Account> accounts = accountDao.findAllAccount();
        for (Account account:accounts){
            System.out.println(account);
        }
        System.out.println("查询成功");
    }*/
    /*查询用户的账户基本信息【查询账户的同时还要有用户的地址信息】*/
    @Test
    public void testFindAllAccountUser(){
        List<UserAccount> usa = accountDao.findAllAccountUser();
        for (Account us:usa){
            System.out.println(us);
        }
        System.out.println("查询成功----");
    }
    /*查询封装之后的用户信息和账户信息
    目的:查询账户以及获取账户下的用户信息
    */
    @Test
    public void testFindAllAccount(){
        List<Account> accounts = accountDao.findAllAccount();
        for (Account account:accounts){
            System.out.println("--------每个account的信息----------");
            System.out.println(account);
            //获取User的值(user早就已经放入Account中了【是主表和从表的关系】)
            System.out.println(account.getUser());
        }
        System.out.println("查询成功");
    }


    /*释放资源*/
    @After
    public void destroy() throws Exception{
        //7.事务提交
        sqlSession.commit();
        //6.释放资源
        sqlSession.close();
        inputStream.close();
    }
}

11.依赖pom.xml

<dependencies>
        <!--sql驱动:连接数据库用-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
        <!--测试的依赖-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <!--日志-->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <!--mybatis环境-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>
    </dependencies>

 

 

 

 

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 游动-白 设计师:上身试试 返回首页