Mapper映射语句高阶应用——ResultMap

    resultMap 元素是 MyBatis 中最重要最强大的元素。它就是让你远离 90% 的需要从结果 集中取出数据的 JDBC 代码的那个东西 , 而且在一些情形下允许你做一些 JDBC 不支持的事 情。 事实上 , 编写相似于对复杂语句联合映射这些等同的代码, 也许可以跨过上千行的代码。 ResultMap 的设计就是简单语句不需要明确的结果映射 , 而很多复杂语句确实需要描述它们 的关系。

    我们通过一个连续的例子,来逐步讲解 ReusltMap 。

    要进行 ResultMap 的实验,先设计数据库:

Mapper映射语句高阶应用——ResultMap

   

上述是数据库的 E-R 图。

create database if not exists mybatis3;

use mybatis3;

drop table if exists tag;
create table if not exists tag(
  id int primary key not null,
  name varchar(100) not null
);

drop table if exists author;
create table if not exists author(
  id int primary key not null,
  username varchar(100) not null,
  password varchar(100) not null,
  email varchar(100),
  bio varchar(100),
  favourite_section varchar(100)
);

drop table if exists blog;
create table if not exists blog(
  id int primary key not null,
  title varchar(100) not null,
  author_id int not null,
  constraint blog_author_fk foreign key(author_id) references author(id)
    on update cascade on delete cascade
);

drop table if exists post;
create table if not exists post(
  id int primary key not null,
  blog_id int not null,
  author_id int not null,
  create_on date not null,
  section varchar(100),
  subject varchar(100),
  draft varchar(100),
  body varchar(200),
  constraint post_blog_fk foreign key(blog_id) references blog(id)
    on update cascade on delete cascade,
  constraint post_author_fk foreign key(author_id) references author(id)
    on update cascade on delete cascade
);

drop table if exists post_tag;
create table if not exists post_tag(
  post_id int not null,
  tag_id int not null,
  primary key(post_id,tag_id),
  constraint postTag_post_fk foreign key(post_id) references post(id)
    on update cascade on delete cascade,
  constraint postTag_tag_fk foreign key(tag_id) references tag(id)
    on update cascade on delete cascade
);

drop table if exists comment;
create table if not exists comment(
  id int primary key not null,
  post_id int not null,
  name varchar(100) not null,
  comment varchar(300),
  constraint comment_post_fk foreign key(post_id) references post(id)
    on update cascade on delete cascade
);