MyBatis数据持久化(七)多表连接查询

来源:互联网 发布:php 魔术引号 编辑:程序博客网 时间:2024/06/05 19:18

本节继续以多表连接查询的案例介绍使用resultMap的好处,对于两张以上的表进行关联查询,当我们有选择的从不同表查询所需字段时,使用resultMap是相当方便的。例如我们有两张表,分别为用户表User和文章Article,通过外键进行关联,属于一对多的关系,一个用户对应多篇文章,我们有查询语句如下:

select u.username,a.title,a.content,a.posttime from article a,user u where u.uid = a.uid and u.username='小王'

查询的字段username属于user表,title、content、posttime属于article表,使用域对象进行映射显然是不合适的,不仅域对象的命名上困难,而且没有任何逻辑可言。如果读者有兴趣可以去看一下hibernate是怎么做的,这里不做介绍。

这时候我们必须使用resultMap进行映射,为了方便演示我们新建一张文章表article,建表语句如下:

CREATE TABLE `mybatis`.`article` (  `AID` INT NOT NULL AUTO_INCREMENT,  `TITLE` VARCHAR(200) NOT NULL,  `POSTTIME` TIME NOT NULL,  `CONTENT` VARCHAR(1600) NOT NULL,  `UID` INT NOT NULL,  PRIMARY KEY (`AID`),  UNIQUE INDEX `AID_UNIQUE` (`AID` ASC),  INDEX `userid_idx` (`UID` ASC),  CONSTRAINT `userid`    FOREIGN KEY (`UID`)    REFERENCES `mybatis`.`user` (`UID`)    ON DELETE NO ACTION    ON UPDATE NO ACTION)ENGINE = InnoDBDEFAULT CHARACTER SET = utf8COLLATE = utf8_unicode_ci;

article表通过外键uid和user表进行关联,接着我们向article表中插入两条数据:

insert into article(TITLE,POSTTIME,CONTENT,UID) values('hello world',CURTIME(),'hello world!',1);insert into article(TITLE,POSTTIME,CONTENT,UID) values('first article',CURTIME(),'first article!',1);

在User.xml中新增配置语句如下:

    <resultMap type="hashmap"  id="queryAticleInfoResult">        <result property="username" column="username"/>        <result property="title" column="title"/>        <result property="content" column="content"/>        <result property="posttime" column="posttime"/>    </resultMap>    <select id="queryAticleInfo" parameterType="hashmap" resultMap="queryAticleInfoResult">        select u.username,a.title,a.content,a.posttime from article a,user u where u.uid = a.uid and u.username=#{username}    </select>

新建测试类com.mybatis.exam5.MultiTableQry,内容如下:

package com.mybatis.exam5;import java.io.IOException;import java.io.Reader;import java.util.ArrayList;import java.util.HashMap;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;public class MultiTableQry {    private Reader reader = null;    private SqlSessionFactory sessionFactory  = null;    private SqlSession session = null;    @Before    public void before()    {        try {            reader = Resources.getResourceAsReader("SqlMapConfig.xml");            sessionFactory = new SqlSessionFactoryBuilder().build(reader);            //创建一个数据库会话             session = sessionFactory.openSession();          } catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }    @Test    @SuppressWarnings({ "rawtypes", "unchecked" })    public void testMultiTableQry()    {        HashMap map = new HashMap();        map.put("username", "小王");        ArrayList list = (ArrayList)session.selectList("User.queryAticleInfo",map);        System.out.println(list);    }    @After    public void after()    {        if(null != session)        {            session.close();        }    }}

我们通过session.selectList方法查询出用户名为'小王'的所有文章信息,该方法返回一个list,list中的每一个元素是一个HashMap对象,每一个对象中存放从数据库中查询出的一条记录。
打开Outline视图,在testMultiTableQry方法上点右键Debug As->Junit Test,控制台中输出:

[    {content=hello world!, title=hello world, username=小王, posttime=09:25:31},    {content=first article!, title=first article, username=小王, posttime=09:25:38}]

可以看到通过resultMap成功將查询结果映射成HashMap。
博文源码:https://github.com/rongbo-j/mybatis-blog

0 0