MyBatis 綜合例子

步驟 1:創(chuàng)建數(shù)據(jù)庫

/*

SQLyog Professional v12.08 (64 bit)

MySQL - 5.7.22-log : Database - mybatis

*********************************************************************

*/

/*!40101 SET NAMES utf8 */;

/*!40101 SET SQL_MODE=''*/;

/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;

/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;

/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;

/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

CREATE DATABASE /*!32312 IF NOT EXISTS*/`mybatis` /*!40100 DEFAULT CHARACTER SET utf8 */;

USE `mybatis`;

/*Table structure for table `author` */

DROP TABLE IF EXISTS `author`;

CREATE TABLE `author` (

? `id` int(11) NOT NULL AUTO_INCREMENT,

? `username` varchar(100) DEFAULT NULL,

? `password` varchar(100) DEFAULT NULL,

? `email` varchar(100) DEFAULT NULL,

? `bio` varchar(100) DEFAULT NULL,

? `favourite_section` varchar(100) DEFAULT NULL,

? PRIMARY KEY (`id`)

) ENGINE=InnoDB AUTO_INCREMENT=306 DEFAULT CHARSET=utf8;

/*Data for the table `author` */

insert? into `author`(`id`,`username`,`password`,`email`,`bio`,`favourite_section`) values (301,'克林頓','123456',' clinton.begin@gmail.com','MyBatis團(tuán)隊(duì)成員','打球'),(302,'布蘭登','123456',' brandon.goodin@gmail.com','MyBatis團(tuán)隊(duì)成員','聽歌'),(303,'亞當(dāng)','123456','adam.gent@evocatus.com','MyBatis團(tuán)隊(duì)貢獻(xiàn)者','游泳');

/*Table structure for table `blog` */

DROP TABLE IF EXISTS `blog`;

CREATE TABLE `blog` (

? `id` int(11) NOT NULL AUTO_INCREMENT,

? `title` varchar(100) DEFAULT NULL,

? `author_id` int(11) DEFAULT NULL,

? `content` varchar(1000) DEFAULT NULL,

? `state` varchar(100) DEFAULT NULL,

? `featured` int(11) DEFAULT NULL,

? PRIMARY KEY (`id`),

? KEY `author_id` (`author_id`)

) ENGINE=InnoDB AUTO_INCREMENT=104 DEFAULT CHARSET=utf8;

/*Data for the table `blog` */

insert? into `blog`(`id`,`title`,`author_id`,`content`,`state`,`featured`) values (101,'MyBatis',301,'MyBatis https://mybatis.org/mybatis-3/','ACTIVE',1),(102,'MyBatis Github',302,'MyBatis Github https://github.com/mybatis/mybatis-3/tree/master/src/site','ACTIVE',2),(103,'MyBatis Blog',303,'MyBatis Blog https://blog.mybatis.org/','INACTIVE',3);

/*Table structure for table `comment` */

DROP TABLE IF EXISTS `comment`;

CREATE TABLE `comment` (

? `id` int(11) NOT NULL AUTO_INCREMENT,

? `post_id` int(11) DEFAULT NULL,

? `name` varchar(100) DEFAULT NULL,

? `comment` varchar(100) DEFAULT NULL,

? PRIMARY KEY (`id`)

) ENGINE=InnoDB AUTO_INCREMENT=605 DEFAULT CHARSET=utf8;

/*Data for the table `comment` */

insert? into `comment`(`id`,`post_id`,`name`,`comment`) values (601,501,'好評1','看起來不錯(cuò)!謝謝@ kazuki43zoo!'),(602,502,'好評2','非常感謝您的幫助@ huan0huan!'),(603,503,'差評3','為什么不保留Java中SQL的靈活性和語法感覺?'),(604,504,'好評4','非常感謝您的解答');

/*Table structure for table `person` */

DROP TABLE IF EXISTS `person`;

CREATE TABLE `person` (

? `id` int(11) NOT NULL AUTO_INCREMENT,

? `username` varchar(100) DEFAULT NULL,

? `password` varchar(100) DEFAULT NULL,

? `full_name` varchar(100) DEFAULT NULL,

? `first_name` varchar(100) DEFAULT NULL,

? `last_name` varchar(100) DEFAULT NULL,

? `date_of_birth` date DEFAULT NULL,

? `created_on` date DEFAULT NULL,

? `update_on` date DEFAULT NULL,

? PRIMARY KEY (`id`)

) ENGINE=InnoDB AUTO_INCREMENT=204 DEFAULT CHARSET=utf8;

/*Data for the table `person` */

insert? into `person`(`id`,`username`,`password`,`full_name`,`first_name`,`last_name`,`date_of_birth`,`created_on`,`update_on`) values (201,'emacarron','123456','愛德華多·馬卡龍','愛德華多','馬卡龍','2000-01-01','2020-01-01','2020-01-02'),(202,'mnesarco','123456','弗蘭克·馬丁內(nèi)斯','弗蘭克','馬丁內(nèi)斯','2000-01-01','2020-01-01','2020-01-02'),(203,'agustafson','123456','安德魯·古斯塔夫森','安德魯','古斯塔夫森','2000-01-01','2020-01-01','2020-01-02');

/*Table structure for table `post` */

DROP TABLE IF EXISTS `post`;

CREATE TABLE `post` (

? `id` int(11) NOT NULL AUTO_INCREMENT,

? `blog_id` int(11) DEFAULT NULL,

? `author_id` int(11) DEFAULT NULL,

? `created_on` date DEFAULT NULL,

? `section` varchar(100) DEFAULT NULL,

? `subject` varchar(100) DEFAULT NULL,

? `draft` int(11) DEFAULT NULL,

? `body` varchar(1000) DEFAULT NULL,

? PRIMARY KEY (`id`)

) ENGINE=InnoDB AUTO_INCREMENT=505 DEFAULT CHARSET=utf8;

/*Data for the table `post` */

insert? into `post`(`id`,`blog_id`,`author_id`,`created_on`,`section`,`subject`,`draft`,`body`) values (501,101,301,'2020-02-01','1','MyBatis 3.5.1',1,'以下是用戶可見更改的列表。用參數(shù)名稱指定的keyProperty可能導(dǎo)致ExecutorException。#1485'),(502,102,302,'2020-02-02','2','MyBatis 3.5.2',1,'以下是用戶可見更改的列表。SQL Builder現(xiàn)在支持LIMIT,OFFSET #1521和FETCH FIRST #1582。'),(503,103,303,'2020-02-03','3','MyBatis 3.5.3',1,'以下是用戶可見更改的列表。在包含的<sql />的CDATA中支持變量替換。#1615'),(504,101,301,'2020-02-01','1','MyBatis 3.5.4',1,'以下是用戶可見更改的列表。用參數(shù)名稱指定的keyProperty可能導(dǎo)致ExecutorException。#4');

/*Table structure for table `post_tag` */

DROP TABLE IF EXISTS `post_tag`;

CREATE TABLE `post_tag` (

? `id` int(11) NOT NULL AUTO_INCREMENT,

? `post_id` int(11) DEFAULT NULL,

? `tag_id` int(11) DEFAULT NULL,

? PRIMARY KEY (`id`)

) ENGINE=InnoDB AUTO_INCREMENT=805 DEFAULT CHARSET=utf8;

/*Data for the table `post_tag` */

insert? into `post_tag`(`id`,`post_id`,`tag_id`) values (801,501,701),(802,502,702),(803,503,703),(804,504,704);

/*Table structure for table `tag` */

DROP TABLE IF EXISTS `tag`;

CREATE TABLE `tag` (

? `id` int(11) NOT NULL AUTO_INCREMENT,

? `name` varchar(100) DEFAULT NULL,

? PRIMARY KEY (`id`)

) ENGINE=InnoDB AUTO_INCREMENT=705 DEFAULT CHARSET=utf8;

/*Data for the table `tag` */

insert? into `tag`(`id`,`name`) values (701,'Alpha'),(702,'Beta'),(703,'RC'),(704,'GA');

/*Table structure for table `users` */

DROP TABLE IF EXISTS `users`;

CREATE TABLE `users` (

? `user_id` int(11) NOT NULL AUTO_INCREMENT,

? `user_name` varchar(100) DEFAULT NULL,

? `hashed_password` varchar(100) DEFAULT NULL,

? `email` varchar(100) DEFAULT NULL,

? PRIMARY KEY (`user_id`)

) ENGINE=InnoDB AUTO_INCREMENT=413 DEFAULT CHARSET=utf8;

/*Data for the table `users` */

insert? into `users`(`user_id`,`user_name`,`hashed_password`,`email`) values (401,'admin','123456','admin@@gmail.com'),(402,'user','123456','user@gmail.com'),(403,'guest','123456','guest@gmail.com'),(411,'test','123456','test@gmail.com'),(412,'test2','123456','test2@gmail.com');

/*Table structure for table `vehicle` */

DROP TABLE IF EXISTS `vehicle`;

CREATE TABLE `vehicle` (

? `id` int(11) NOT NULL AUTO_INCREMENT,

? `vin` varchar(100) DEFAULT NULL,

? `year` varchar(100) DEFAULT NULL,

? `make` varchar(100) DEFAULT NULL,

? `model` varchar(100) DEFAULT NULL,

? `color` varchar(100) DEFAULT NULL,

? `vehicle_type` int(11) DEFAULT NULL,

? `door_count` int(11) DEFAULT NULL,

? `box_size` int(11) DEFAULT NULL,

? PRIMARY KEY (`id`)

) ENGINE=InnoDB AUTO_INCREMENT=904 DEFAULT CHARSET=utf8;

/*Data for the table `vehicle` */

insert? into `vehicle`(`id`,`vin`,`year`,`make`,`model`,`color`,`vehicle_type`,`door_count`,`box_size`) values (901,'奔馳汽車','1883','德國奔馳汽車公司','AMG GT4','綠色',1,2,NULL),(902,'麥克卡車','1940','麥克制造公司','Mack NR','白色',2,NULL,4),(903,'雷諾貨車','1941','美國雷諾貨車公司','LCV','紅色',3,NULL,NULL);

/* Procedure structure for procedure `getBlogsAndAuthors` */

/*!50003 DROP PROCEDURE IF EXISTS? `getBlogsAndAuthors` */;

DELIMITER $$

/*!50003 CREATE DEFINER=`root`@`localhost` PROCEDURE `getBlogsAndAuthors`(IN blog_id INT, IN author_id INT)

BEGIN

SELECT * FROM BLOG WHERE ID = blog_id;

SELECT * FROM AUTHOR WHERE ID = author_id;

END */$$

DELIMITER ;

/* Procedure structure for procedure `getBlogsAndPosts` */

/*!50003 DROP PROCEDURE IF EXISTS? `getBlogsAndPosts` */;

DELIMITER $$

/*!50003 CREATE DEFINER=`root`@`localhost` PROCEDURE `getBlogsAndPosts`(IN in_id INT)

BEGIN

SELECT * FROM BLOG WHERE ID = in_id;

SELECT * FROM POST WHERE BLOG_ID = in_id;

END */$$

DELIMITER ;

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;

/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;

/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;

/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

步驟 2:使用IDE創(chuàng)建Maven項(xiàng)目

<project xmlns="http://maven.apache.org/POM/4.0.0"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>

<groupId>org.mybatis</groupId>

<artifactId>example</artifactId>

<version>0.0.1-SNAPSHOT</version>

<name>example</name>

<description>example</description>

<dependencies>

<dependency>

<groupId>org.mybatis</groupId>

<artifactId>mybatis</artifactId>

<version>3.5.4</version>

</dependency>

<dependency>

<groupId>mysql</groupId>

<artifactId>mysql-connector-java</artifactId>

<version>5.1.48</version>

</dependency>

<dependency>

<groupId>log4j</groupId>

<artifactId>log4j</artifactId>

<version>1.2.17</version>

</dependency>

<dependency>

<groupId>junit</groupId>

<artifactId>junit</artifactId>

<version>4.12</version>

</dependency>

</dependencies>

</project>

步驟 3:配置MyBatis

driver=com.mysql.jdbc.Driver

url=jdbc:mysql://127.0.0.1:3306/mybatis

username=root

password_dev=123456

password_pro=12345678

<?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>

<!-- 屬性(properties) -->

<properties resource="org/mybatis/example/config.properties">

<!-- <property name="username" value="root" /> -->

<!-- <property name="password" value="123456" /> -->

</properties>

<!-- 設(shè)置(settings) -->

<settings>

<setting name="cacheEnabled" value="true" />

<setting name="autoMappingBehavior" value="PARTIAL" />

<setting name="logImpl" value="LOG4J" />

</settings>

<!-- 類型別名(typeAliases) -->

<!-- <typeAliases> -->

<!-- <typeAlias alias="Blog" type="org.mybatis.example.Blog" /> -->

<!-- </typeAliases> -->

<typeAliases>

<package name="org.mybatis.example.domain" />

</typeAliases>

<!-- 環(huán)境配置(environments) -->

<environments default="development">

<environment id="development">

<transactionManager type="JDBC" />

<dataSource type="POOLED">

<property name="driver" value="${driver}" />

<property name="url" value="${url}" />

<property name="username" value="${username}" />

<property name="password" value="${password_dev}" />

</dataSource>

</environment>

<environment id="production">

<transactionManager type="JDBC" />

<dataSource type="POOLED">

<property name="driver" value="${driver}" />

<property name="url" value="${url}" />

<property name="username" value="${username}" />

<property name="password" value="${password_pro}" />

</dataSource>

</environment>

</environments>

<!-- 數(shù)據(jù)庫廠商標(biāo)識(shí)(databaseIdProvider) -->

<databaseIdProvider type="DB_VENDOR">

<property name="MySQL" value="mysql" />

<property name="SQL Server" value="sqlserver" />

<property name="DB2" value="db2" />

<property name="Oracle" value="oracle" />

</databaseIdProvider>

<!-- 映射器(mappers) -->

<!-- <mappers> -->

<!-- <mapper resource="org/mybatis/example/BlogMapper.xml" /> -->

<!-- <mapper resource="org/mybatis/example/PersonMapper.xml" /> -->

<!-- </mappers> -->

<mappers>

<package name="org.mybatis.example.mapper" />

</mappers>

</configuration>

# 全局日志配置

log4j.rootLogger=ERROR, stdout

# MyBatis 日志配置

log4j.logger.org.mybatis.example=DEBUG

# 控制臺(tái)輸出

log4j.appender.stdout=org.apache.log4j.ConsoleAppender

log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

步驟 4:創(chuàng)建MyBatis工具類

package org.mybatis.example.util;

import java.io.IOException;

import java.io.InputStream;

import org.apache.ibatis.io.Resources;

import org.apache.ibatis.session.SqlSession;

import org.apache.ibatis.session.SqlSessionFactory;

import org.apache.ibatis.session.SqlSessionFactoryBuilder;

/**

* MyBatis工具類

*

* @author 大強(qiáng)

*

*/

public class MyBatisUtil {

public static SqlSessionFactory sqlSessionFactory;

static {

try {

// 從類路徑下加載資源文件mybatis-config.xml

String resource = "org/mybatis/example/mybatis-config.xml";

InputStream inputStream = Resources.getResourceAsStream(resource);

// 由 SqlSessionFactoryBuilder創(chuàng)建SqlSessionFactory

sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

} catch (IOException e) {

e.printStackTrace();

}

}

/**

* 由 SqlSessionFactory創(chuàng)建SqlSession

*

* @return

*/

public static SqlSession getSqlSession() {

return sqlSessionFactory.openSession();

}

/**

* 關(guān)閉SqlSession

*

* @param sqlSession

*/

public static void closeSqlSession(SqlSession sqlSession) {

if (sqlSession != null) {

sqlSession.close();

}

}

}

步驟 5:創(chuàng)建POJO類

package org.mybatis.example.domain;

/**

* 作者POJO類

*

* @author 大強(qiáng)

*

*/

public class Author {

public int id;

// public int authorid;

public String username;

public String password;

public String email;

public String bio;

public String favouriteSection;

// public int getAuthorid() {

// return authorid;

// }

//

// public void setAuthorid(int authorid) {

// this.authorid = authorid;

// }

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 getPassword() {

return password;

}

public void setPassword(String password) {

this.password = password;

}

public String getEmail() {

return email;

}

public void setEmail(String email) {

this.email = email;

}

public String getBio() {

return bio;

}

public void setBio(String bio) {

this.bio = bio;

}

public String getFavouriteSection() {

return favouriteSection;

}

public void setFavouriteSection(String favouriteSection) {

this.favouriteSection = favouriteSection;

}

}

package org.mybatis.example.domain;

import java.util.List;

/**

* 博客POJO類

*

* @author 大強(qiáng)

*

*/

public class Blog {

public int id;

public String title;

public String authorId;

public String content;

public String state;

// 一對一

// 作者

public Author author;

// 一對多

// 文章

public List<Post> posts;

public Blog(Integer id) {

super();

this.id = id;

}

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 getAuthorId() {

return authorId;

}

public void setAuthorId(String authorId) {

this.authorId = authorId;

}

public String getContent() {

return content;

}

public void setContent(String content) {

this.content = content;

}

public Author getAuthor() {

return author;

}

public void setAuthor(Author author) {

this.author = author;

}

public List<Post> getPosts() {

return posts;

}

public void setPosts(List<Post> posts) {

this.posts = posts;

}

public String getState() {

return state;

}

public void setState(String state) {

this.state = state;

}

}

package org.mybatis.example.domain;

/**

* 汽車POJO類

*

* @author 大強(qiáng)

*

*/

public class Car extends Vehicle {

// Car

public String doorCount;

public String getDoorCount() {

return doorCount;

}

public void setDoorCount(String doorCount) {

this.doorCount = doorCount;

}

}

package org.mybatis.example.domain;

/**

* 評論P(yáng)OJO類

*

* @author 大強(qiáng)

*

*/

public class Comment {

public int id;

public int postId;

public String name;

public String comment;

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

public int getPostId() {

return postId;

}

public void setPostId(int postId) {

this.postId = postId;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String getComment() {

return comment;

}

public void setComment(String comment) {

this.comment = comment;

}

}

package org.mybatis.example.domain;

/**

* 草稿文章POJO類

*

* @author 大強(qiáng)

*

*/

public class DraftPost extends Post {

public String draftBody;

public String getDraftBody() {

return draftBody;

}

public void setDraftBody(String draftBody) {

this.draftBody = draftBody;

}

}

package org.mybatis.example.domain;

import java.util.Date;

/**

* 人員POJO類

*

* @author 大強(qiáng)

*

*/

public class Person {

public int id;

public String username;

public String password;

public String fullName;

public String firstName;

public String lastName;

public Date dateOfBirth;

public Date createdOn;

public Date updateOn;

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 getPassword() {

return password;

}

public void setPassword(String password) {

this.password = password;

}

public String getFullName() {

return fullName;

}

public void setFullName(String fullName) {

this.fullName = fullName;

}

public String getFirstName() {

return firstName;

}

public void setFirstName(String firstName) {

this.firstName = firstName;

}

public String getLastName() {

return lastName;

}

public void setLastName(String lastName) {

this.lastName = lastName;

}

public Date getDateOfBirth() {

return dateOfBirth;

}

public void setDateOfBirth(Date dateOfBirth) {

this.dateOfBirth = dateOfBirth;

}

public Date getCreatedOn() {

return createdOn;

}

public void setCreatedOn(Date createdOn) {

this.createdOn = createdOn;

}

public Date getUpdateOn() {

return updateOn;

}

public void setUpdateOn(Date updateOn) {

this.updateOn = updateOn;

}

}

package org.mybatis.example.domain;

import java.util.Date;

import java.util.List;

/**

* 文章POJO類

*

* @author 大強(qiáng)

*

*/

public class Post {

public int id;

public int blogId;

public int authorId;

public Date createdOn;

public String section;

public String subject;

public String draft;

public String body;

public Author author;

public List<Comment> comments;

public List<Tag> tags;

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

public int getBlogId() {

return blogId;

}

public void setBlogId(int blogId) {

this.blogId = blogId;

}

public int getAuthorId() {

return authorId;

}

public void setAuthorId(int authorId) {

this.authorId = authorId;

}

public Date getCreatedOn() {

return createdOn;

}

public void setCreatedOn(Date createdOn) {

this.createdOn = createdOn;

}

public String getSection() {

return section;

}

public void setSection(String section) {

this.section = section;

}

public String getSubject() {

return subject;

}

public void setSubject(String subject) {

this.subject = subject;

}

public String getDraft() {

return draft;

}

public void setDraft(String draft) {

this.draft = draft;

}

public String getBody() {

return body;

}

public void setBody(String body) {

this.body = body;

}

public List<Comment> getComments() {

return comments;

}

public void setComments(List<Comment> comments) {

this.comments = comments;

}

public List<Tag> getTags() {

return tags;

}

public void setTags(List<Tag> tags) {

this.tags = tags;

}

public Author getAuthor() {

return author;

}

public void setAuthor(Author author) {

this.author = author;

}

}

package org.mybatis.example.domain;

/**

* 標(biāo)簽POJO類

*

* @author 大強(qiáng)

*

*/

public class Tag {

public int id;

public String name;

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

}

package org.mybatis.example.domain;

/**

* 卡車POJO類

*

* @author 大強(qiáng)

*

*/

public class Truck extends Vehicle {

// Truck

public String boxSize;

public String getBoxSize() {

return boxSize;

}

public void setBoxSize(String boxSize) {

this.boxSize = boxSize;

}

}

package org.mybatis.example.domain;

/**

* 用戶POJO類

*

* @author 大強(qiáng)

*

*/

public class User {

public int id;

public String username;

public String password;

// public String hashedPassword;

public String email;

// public User(Integer id, String username, String password) {

// super();

// this.id = id;

// this.username = username;

// this.password = password;

// }

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 getPassword() {

return password;

}

public void setPassword(String password) {

this.password = password;

}

// public String getHashedPassword() {

// return hashedPassword;

// }

//

// public void setHashedPassword(String hashedPassword) {

// this.hashedPassword = hashedPassword;

// }

public String getEmail() {

return email;

}

public void setEmail(String email) {

this.email = email;

}

}

package org.mybatis.example.domain;

/**

* 車輛POJO類

*

* @author 大強(qiáng)

*

*/

public class Vehicle {

public int id;

public String vin;

public String year;

public String make;

public String model;

public String color;

// 1:Car 2:Truck

public String vehicleType;

// Car

// public String doorCount;

// Truck

// public String boxSize;

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

public String getVin() {

return vin;

}

public void setVin(String vin) {

this.vin = vin;

}

public String getYear() {

return year;

}

public void setYear(String year) {

this.year = year;

}

public String getMake() {

return make;

}

public void setMake(String make) {

this.make = make;

}

public String getModel() {

return model;

}

public void setModel(String model) {

this.model = model;

}

public String getColor() {

return color;

}

public void setColor(String color) {

this.color = color;

}

public String getVehicleType() {

return vehicleType;

}

public void setVehicleType(String vehicleType) {

this.vehicleType = vehicleType;

}

}

步驟 6:創(chuàng)建映射器接口類

package org.mybatis.example.mapper;

import java.util.List;

import org.mybatis.example.domain.Blog;

/**

* 博客映射器

*

* @author 大強(qiáng)

*

*/

public interface BlogMapper {

List<Blog> selectBlogDetails(int id);

}

步驟 7:創(chuàng)建映射器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="org.mybatis.example.mapper.BlogMapper">

<!-- 非常復(fù)雜的語句 -->

<select id="selectBlogDetails" resultMap="detailedBlogResultMap">

select

B.id as blog_id,

B.title as blog_title,

B.author_id as blog_author_id,

A.id as author_id,

A.username as author_username,

A.password as author_password,

A.email as

author_email,

A.bio as author_bio,

A.favourite_section as

author_favourite_section,

P.id as post_id,

P.blog_id as post_blog_id,

P.author_id as post_author_id,

P.created_on as post_created_on,

P.section as post_section,

P.subject as post_subject,

P.draft as draft,

P.body as post_body,

C.id as comment_id,

C.post_id as comment_post_id,

C.name as comment_name,

C.comment as comment_text,

T.id as tag_id,

T.name as tag_name

from Blog B

left outer join Author A on B.author_id =

A.id

left outer join Post P on B.id = P.blog_id

left outer join Comment

C on P.id = C.post_id

left outer join Post_Tag PT on PT.post_id = P.id

left outer join Tag T on PT.tag_id = T.id

where B.id = #{id}

</select>

<resultMap id="detailedBlogResultMap" type="Blog">

<constructor>

<idArg column="blog_id" javaType="int" />

</constructor>

<result property="title" column="blog_title" />

<association property="author" javaType="Author">

<id property="id" column="author_id" />

<result property="username" column="author_username" />

<result property="password" column="author_password" />

<result property="email" column="author_email" />

<result property="bio" column="author_bio" />

<result property="favouriteSection"

column="author_favourite_section" />

</association>

<collection property="posts" ofType="Post">

<id property="id" column="post_id" />

<result property="subject" column="post_subject" />

<association property="author" javaType="Author" />

<collection property="comments" ofType="Comment">

<id property="id" column="comment_id" />

</collection>

<collection property="tags" ofType="Tag">

<id property="id" column="tag_id" />

</collection>

<discriminator javaType="int" column="draft">

<case value="1" resultMap="draftPostResult" />

</discriminator>

</collection>

</resultMap>

<resultMap id="draftPostResult" type="DraftPost">

<result property="subject" column="post_subject" />

<result property="draftBody" column="post_body" />

</resultMap>

</mapper>

package org.mybatis.example.mapper;

import java.util.List;

import org.apache.ibatis.session.SqlSession;

import org.apache.log4j.Logger;

import org.junit.Test;

import org.mybatis.example.domain.Blog;

import org.mybatis.example.util.MyBatisUtil;

/**

* Author測試類

*

* @author 大強(qiáng)

*

*/

public class BlogMapperTest {

Logger logger = Logger.getLogger(BlogMapperTest.class);

// 注意:選中方法名,單擊鼠標(biāo)右鍵,選擇 Run as -> JUnit Test,就能執(zhí)行單個(gè)方法。

/**

* 非常復(fù)雜的結(jié)果映射測試方法

*/

@Test

public void detailedBlogResultMapTest() {

logger.info("非常復(fù)雜的結(jié)果映射開始...");

SqlSession session = MyBatisUtil.getSqlSession();

BlogMapper mapper = session.getMapper(BlogMapper.class);

List<Blog> list = mapper.selectBlogDetails(101);

if (list != null) {

for (Blog blog : list) {

logger.info(blog.getId());

logger.info(blog.getTitle());

}

}

MyBatisUtil.closeSqlSession(session);

logger.info("非常復(fù)雜的結(jié)果映射結(jié)束");

}

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,316評論 6 531
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,481評論 3 415
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,241評論 0 374
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,939評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 71,697評論 6 409
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,182評論 1 324
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,247評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,406評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 48,933評論 1 334
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 40,772評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 42,973評論 1 369
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,516評論 5 359
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 44,209評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,638評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,866評論 1 285
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 51,644評論 3 391
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 47,953評論 2 373

推薦閱讀更多精彩內(nèi)容