在上章的 一对多 中,我们已经学习如何在 mybatis 中关联多表,但在实际项目中也是经常使用 多对一 的情况,这些查询是如何处理的呢,在这一节中我们来学习它。多表映射的多对一关系要用到 mybitis 的 association 来加以实现。这篇介绍的是多表中的多对一表关联查询。
应用场景:首先根据帖子 id 读取一个帖子信息,然后再读取这个帖子所属的用户信息。
user表的结构和数据:
-- ---------------------------- -- table structure for `user` -- ---------------------------- create table `user` ( `id` int(10) unsigned not null auto_increment, `username` varchar(64) not null default '', `mobile` int(10) unsigned not null default '0', `created` datetime not null default '0000-00-00 00:00:00', primary key (`id`) ) engine=innodb auto_increment=2 default charset=utf8; -- ---------------------------- -- records of user -- ---------------------------- insert into `user` values ('1', 'h3', '100', '2015-09-23 20:11:23');
帖子表 post 的结构和数据:
-- ----------------------------
-- table structure for `post`
-- ----------------------------
create table `post` (
`post_id` int(10) unsigned not null auto_increment,
`userid` int(10) unsigned not null,
`title` varchar(254) not null default '',
`content` text,
`created` datetime not null default '0000-00-00 00:00:00',
primary key (`post_id`)
) engine=innodb auto_increment=4 default charset=utf8;
-- ----------------------------
-- records of post
-- ----------------------------
insert into `post` values ('1', '1', 'mybatis关联数据查询', '在实际项目中,经常使用关联表的查询,比如:多对一,一对多等。这些查询是如何处理的呢,这一讲就讲这个问题。我们首先创建一个 post 表,并初始化数据.', '2015-09-23 21:40:17');
insert into `post` values ('2', '1', 'mybatis开发环境搭建', '为了方便学习,这里直接建立java 工程,但一般都是开发 web 项目。', '2015-09-23 21:42:14');
insert into `post` values ('3', '2', '这个是别人发的', 'content,内容...', '0000-00-00 00:00:00');
从上面应该看出,这几个帖子对应的 userid 都是1,所以需要用户表 user 里面有 id=1 的数据。可以修改成满足自己条件的数据,按照 orm 的规则,表肯定需要一个对象与之对应,所以我们增加一个 post 类。
这个例子中,我们需要在包 com.h3.pojo 下创建两个类,它们分别是: user.java 和 post.java,我们一个一个地来看它们的代码,user.java 类的代码如下:
package com.h3.pojo; import java.io.serializable; import java.util.date; import java.util.list; public class user implements serializable{ private int id; private string username; private string mobile; private list<post> posts; public int getid() { return id; } public void setid(int id) { this.id = id; } public string getusername() { return username; } public void setusername(string username) { this.username = username; } public string getmobile() { return mobile; } public void setmobile(string mobile) { this.mobile = mobile; } public list<post> getposts() { return posts; } public void setposts(list<post> posts) { this.posts = posts; } @override public string tostring() { return "user [id=" + id + ", name=" + username + "]"; } }post.java 类的代码如下:
package com.h3.pojo; import java.io.serializable; public class post implements serializable{ private int id; private user user; private string title; private string content; public int getid() { return id; } public void setid(int id) { this.id = id; } public user getuser() { return user; } public void setuser(user user) { this.user = user; } public string gettitle() { return title; } public void settitle(string title) { this.title = title; } public string getcontent() { return content; } public void setcontent(string content) { this.content = content; } }
在这一章节中,要用到的配置文件有两个,一个是 mybatis 的主配置文件:src/config/configure.xml 和 user.java对应的配置文件 user.xml,我们先来看看 src/config/configure.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> <typealias alias="user" type="com.h3.pojo.user" /> <typealias alias="post" type="com.h3.pojo.post" /> </typealiases> <environments default="development"> <environment id="development"> <transactionmanager type="jdbc" /> <datasource type="pooled"> <property name="driver" value="com.mysql.jdbc.driver" /> <property name="url" value="jdbc:mysql://127.0.0.1:3306/h3" /> <property name="username" value="root" /> <property name="password" value="" /> </datasource> </environment> </environments> <mappers> <!-- // power by http://www.h3.com --> <mapper resource="com/h3/pojo/user.xml" /> </mappers> </configuration>这里需要注意的是 <typealiases> 这个标签内容,它就是用于定义一个 javabean 类的别名,如将 com.h3.pojo.user 简写为 user,可以认为 com.h3.pojo.user 就是 user,user 就是 com.h3.pojo.user 。
另外一个配置文件 user.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.h3.usermaper"> <!-- user 级联文章查询 方法配置 (多个文章对一个用户) --> <resultmap type="post" id="resultpostsmap"> <result property="id" column="post_id" /> <result property="title" column="title" /> <result property="content" column="content" /> <association property="user" javatype="user"> <id property="id" column="userid"/> <result property="username" column="username"/> <result property="mobile" column="mobile"/> </association> </resultmap> <select id="getposts" resultmap="resultpostsmap" parametertype="int"> select u.*,p.* from user u, post p where u.id=p.userid and p.post_id=#{post_id} </select> </mapper>
注:在上面的配置文件中,使用到了一个 <association>标签,关联对应的 user 类。
到这里,整个工作准备得已经差不多了,我们创建一个主类来测试上面程序,在 src 下创建一个 main.java,代码如下:
import java.io.reader; import java.text.messageformat; import java.util.list; 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 com.h3.pojo.post; import com.h3.pojo.user; public class main { private static sqlsessionfactory sqlsessionfactory; private static reader reader; static { try { reader = resources.getresourceasreader("config/configure.xml"); sqlsessionfactory = new sqlsessionfactorybuilder().build(reader); } catch (exception e) { e.printstacktrace(); } } public static sqlsessionfactory getsession() { return sqlsessionfactory; } /** * @param args */ public static void main(string[] args) { // todo auto-generated method stub sqlsession session = sqlsessionfactory.opensession(); try { int postid = 1; post post = session.selectone("com.h3.usermaper.getposts", postid); system.out.println("title: "+post.gettitle()); system.out.println("username: "+post.getuser().getusername()); } finally { session.close(); } } }
输出结果如下:
title: mybatis关联数据查询 username: h3
附工程目录结构图如下: