Mybatis关联关系配置(一对多对一)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Mybatis关联关系配置(一对多对一)相关的知识,希望对你有一定的参考价值。

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关联关系配置(一对多对一)的主要内容,如果未能解决你的问题,请参考以下文章

MyBatis_关联关系查询

Hibernate关联关系配置(一对多一对一和多对多)

MyBatis框架关联映射

hibernate 关联关系(多对多对多一对一)的配置

MyBatis关联映射

mytabits表关联一对一(多对一?)