Java教程

mybatis的基础应用03多表操作一对多案例

本文主要是介绍mybatis的基础应用03多表操作一对多案例,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

项目结构

在这里插入图片描述

需要的jar包

链接: https://pan.baidu.com/s/1VT8E0YGBViNM76i-fo-cyQ 提取码: qft5 

数据库表sql

DROP TABLE IF EXISTS `user`;

CREATE TABLE `user` (
  `id` int(11) NOT NULL auto_increment,
  `username` varchar(32) NOT NULL COMMENT '用户名称',
  `birthday` datetime default NULL COMMENT '生日',
  `sex` char(1) default NULL COMMENT '性别',
  `address` varchar(256) default NULL COMMENT '地址',
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;



insert  into `user`(`id`,`username`,`birthday`,`sex`,`address`) values (41,'李雪山','2020-02-27 17:47:08','男','郑州'),(42,'李家诚','2020-03-02 15:09:37','男','郑州高新区'),(43,'马玥','2020-03-04 11:34:34','女','郑州高新区'),(45,'袁可可','2020-03-04 12:04:06','男','郑州高新区'),(46,'范彦辉','2020-03-07 17:37:26','男','郑州'),(48,'吴天放','2020-03-08 11:44:00','男','郑州中原区');





DROP TABLE IF EXISTS `account`;

CREATE TABLE `account` (
  `ID` int(11) NOT NULL COMMENT '编号',
  `UID` int(11) default NULL COMMENT '用户编号',
  `MONEY` double default NULL COMMENT '金额',
  PRIMARY KEY  (`ID`),
  KEY `FK_Reference_8` (`UID`),
  CONSTRAINT `FK_Reference_8` FOREIGN KEY (`UID`) REFERENCES `user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;



insert  into `account`(`ID`,`UID`,`MONEY`) values (1,41,1000),(2,45,1000),(3,41,2000);


mybatis-config.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>
<!--  给实体类起别名  -->
<typeAliases>
    <package name="cn.yh.model"/>
</typeAliases>
<!--  环境配置  -->
    <environments default="mysql">
        <environment id="mysql">
<!--      事物管理      -->
            <transactionManager type="JDBC"/>
<!--      数据;源      -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
<!--  指定映射文件的位置  -->
    <mappers>
        <mapper resource="cn/yh/dao/UserDao.xml"/>
        <mapper resource="cn/yh/dao/AccountDao.xml"/>
    </mappers>
</configuration>

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

实体类User

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


    /**
     * 查询用户,同时得到该用户拥有的账户信息
     * 一个用户可以包含多个账户
     * 一对多查询
     * 在一的一方的类中包含一个Account类型的集合属性accounts
     */
    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 Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public char getSex() {
        return sex;
    }

    public void setSex(char 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 + '\'' +
                '}';
    }
}

实体类Account

public class Account implements Serializable {
    private Integer id;
    private Integer uid;
    private Double money;
    /**
     * 查询账户信息,同时得到对应的用户信息
     * 多个账户属于一个用户(一个账户只能属于一个用户)
     * 多对一查询(一对一查询)
     * Account类中包含一个User类型的属性
     */
    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;
    }

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

}

实体类AccountUser

public class AccountUser extends Account{
    private String username;
    private char sex;
    private String address;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public char getSex() {
        return sex;
    }

    public void setSex(char sex) {
        this.sex = sex;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return super.toString()+"AccountUser{" +
                "username='" + username + '\'' +
                ", sex=" + sex +
                ", address='" + address + '\'' +
                '}';
    }
}

dao层UserDao

public interface UserDao {
    /**
     * 查询所有数据
     * @return
     */
    List<User> findAll();
}

dao层UserDao对应的UserDao.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.yh.dao.UserDao">
<!--  做映射  -->
    <resultMap id="userMap" type="cn.yh.model.User">
        <id column="id" property="id" />
        <result column="username" property="username"/>
        <result column="birthday" property="birthday"/>
        <result column="sex" property="sex"/>
        <result column="address" property="address"/>
<!--    collection标签用来处理集合属性
        property指定属性名
        ofType指定集合中的数据类型-->
        <collection property="accounts" ofType="Account">
            <id column="aid" property="id"/>
            <result column="uid" property="uid"/>
            <result column="money" property="money"/>
        </collection>
    </resultMap>
    <select id="findAll" resultMap="userMap">
       SELECT u.*,a.id aid,a.uid,a.money
       FROM user u left join account a
       on u.id=a.uid;
    </select>
</mapper>

dao层AccountDao

public interface AccountDao {
    /**
     * 查询所有账户信息
     * @return
     */
    List<Account> findAll();

    /**
     *查询所有账户信息,并查询账户对应的用户信息
     * @return
     */
    List<AccountUser> findAllAccountUser();
}

dao层UserDao对应的AccountDao.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.yh.dao.AccountDao">
    <resultMap id="accountMap" type="cn.yh.model.Account">
        <id column="aid" property="id"/>
        <result column="uid" property="uid"/>
        <result column="money" property="money"/>
        <!--    association标签:用来操作实体类类型的属性
        property表示属性名
        javaType表示属性的类型    -->

        <association property="user" javaType="User">
            <id column="id" property="id"/>
            <result column="username" property="username"/>
            <result column="birthday" property="birthday"/>
            <result column="sex" property="sex"/>
            <result column="address" property="address"/>
        </association>
    </resultMap>

<!--  查询所有账户  -->
    <select id="findAll" resultMap="accountMap">
        SELECT u.`*`,a.ID aid,a.UID,a.MONEY
        FROM account a
        LEFT join user u
        ON a.UID=u.id;
    </select>
<!--  查询所有账户并得到账户对应的用户信息  -->
    <select id="findAllAccountUser" resultType="AccountUser">
        SELECT a.`*`,u.username,u.sex,u.address
        FROM account a
        LEFT join user u
        ON a.UID=u.id;
    </select>
</mapper>

测试类UserTest

public class UserTest {
    private InputStream resourceAsStream;
    private SqlSession sqlSession;
    private UserDao mapper;
    @Before
    public void init() throws IOException {
        //1、读取配置文件
         resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
         //2、创建SqlSessionFactoryBuilder工厂对象
        SqlSessionFactoryBuilder sqlSessionFactory = new SqlSessionFactoryBuilder();
        SqlSessionFactory build = sqlSessionFactory.build(resourceAsStream);
        //3、得到SqlSession对象
         sqlSession = build.openSession();
         //4 通过SqlSession获得接口的代理对象
        mapper = sqlSession.getMapper(UserDao.class);
    }
    @After
    public void destory(){
        sqlSession.commit();
        if (sqlSession!=null){
            sqlSession.close();
        }
        if (resourceAsStream!=null){
            try {
                resourceAsStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    @org.junit.Test
    public void testFindAll(){
        List<User> all = mapper.findAll();
        for (User user : all) {
            System.out.println(user);
            List<Account> accounts = user.getAccounts();
            for (Account account : accounts) {
                System.out.println(account);
            }
        }
    }

}

测试类AccountTest

public class AccountTest {
    private InputStream resourceAsStream;
    private SqlSession sqlSession;
    private AccountDao mapper;

    @Before
    public void init() throws IOException {
        //1、读取配置文件
        resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
        //2、创建SqlSessionFactoryBuilder工厂对象
        SqlSessionFactoryBuilder sqlSessionFactory = new SqlSessionFactoryBuilder();
        SqlSessionFactory build = sqlSessionFactory.build(resourceAsStream);
        //3、得到SqlSession对象
        sqlSession = build.openSession();
        //4 通过SqlSession获得接口的代理对象
        mapper = sqlSession.getMapper(AccountDao.class);
    }
    @After
    public void destory(){
        sqlSession.commit();
        if (sqlSession!=null){
            sqlSession.close();
        }
        if (resourceAsStream!=null){
            try {
                resourceAsStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    @org.junit.Test
    public void testFindAll(){
        List<Account> all = mapper.findAll();
        for (Account user : all) {
            System.out.println(user);
            System.out.println(user.getUser());
        }
    }
    @org.junit.Test
    public void testFindAllAccountUser(){
        List<AccountUser> allAccountUser = mapper.findAllAccountUser();
        for (AccountUser accountUser : allAccountUser) {
            System.out.println(accountUser);
        }
    }

}
这篇关于mybatis的基础应用03多表操作一对多案例的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!