标签:1.5   3.0   where   names   name   lin   author   factory   stat   
BlogMapper.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.cj.dao.BlogDao">
<!-- 定义Blog的resultMap。id值用于标识resultMap,type值为resultMap的结果类型 -->
	<resultMap type="Blog" id="Blogresult">
	<!--  基本数据类型映射。column为数据库的列,property为该列所对应的Java属性 -->
		<id column="id" property="id"/>
		<result column="title" property="title"/>
		<result column="content" property="content"/>
		<result column="createTime" property="createTime"/>
		<!-- 配置关联对象。其中:
			property属性值为当前Blog对象的关联对象名;
			javaType属性值为关联对象属性所属的完全限定类名或别名;
			select属性值为所请求的select映射的ID,该select使用子查询获取其所关联的属性对象;
			column属性值为传给子查询的字段,即外键列  -->
		
		<association property="author" javaType="Author" select="getAuthor" column="author_id"/>
	
	</resultMap>
	<select id="getAuthor" parameterType="int" resultType="Author">
		select * from Author where id = #{id}
	</select>
	
	<select id="getBlog" parameterType="int" resultMap="Blogresult">
		select * from blog where id = #{id}
	</select>
</mapper>
 
 
BlogDao 
package com.cj.dao;
import com.cj.entity.Author;
import com.cj.entity.Blog;
public interface BlogDao {
	//根据博客id查询信息
	public Blog getBlog(int id);
	
	//根据作者id查询作者信息
	public Author getAuthor(int id);
}
 
Blog实体类package com.cj.entity;
 
import java.util.Date;
public class Blog {
	private int id;
	private String title;
	private String content;
	private Date createTime;
	private Author author;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	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;
	}
	public Date getCreateTime() {
		return createTime;
	}
	public void setCreateTime(Date createTime) {
		this.createTime = createTime;
	}
	public Author getAuthor() {
		return author;
	}
	public void setAuthor(Author author) {
		this.author = author;
	}
	public Blog() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Blog(String title, String content, Date createTime,
			Author author) {
		super();
		this.title = title;
		this.content = content;
		this.createTime = createTime;
		this.author = author;
	}
}
 test测试类
public static void main(String[] args) throws Exception {
		 SqlSession openSession = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("config.xml")).openSession();
		 BlogDao mapper = openSession.getMapper(BlogDao.class);
		 //根据博客id查询信息(包含作者)
		 Blog blog = mapper.getBlog(1);
		 System.out.println(blog.getTitle());
		 System.out.println(blog.getAuthor().getUsername());
	}
 
Mybatis关联关系配置(一对一、多对一)
标签:1.5   3.0   where   names   name   lin   author   factory   stat   
原文地址:http://www.cnblogs.com/cj870522/p/6368183.html