(1)首先,创建数据库mybatismanytoone并插入数据
create database mybatismanytoone; use mybatismanytoone; 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) ); INSERT INTO user VALUES ('1', 'yiibai', '100', '2015-09-23 20:11:23'); 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; 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');
(2)接着我们创建两个java bean Post.java和User.java
Post.java
package mybatis.bean; 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; } }
User.java
package mybatis.bean; 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 + "]"; } }
(3)其次,我们创建config/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> <typeAlias alias="User" type="mybatis.bean.User" /> <typeAlias alias="Post" type="mybatis.bean.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://localhost:3306/mybatismanytoone"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> <mappers> <!-- // power by http://www.yiibai.com --> <mapper resource="mybatis/bean/User.xml" /> </mappers> </configuration>
(4)再次,我们创建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.mybatis.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>
(5)最后,我们执行main函数,进行查询
package Main; import java.io.Reader; import mybatis.bean.Post; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class Main { private static SqlSessionFactory sqlSessionFactory; private static Reader reader; static { try { reader = Resources.getResourceAsReader("config/config.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.zk.userMaper", postId); System.out.println("title: "+post.getTitle()); System.out.println("userName: "+post.getUser().getUsername()); } finally { session.close(); } } }
查询结果如下图显示:
程序结构如下图所示: