MyBatis 綜合例子

步驟 1:創建數據庫

/*
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','	[email protected]','MyBatis團隊成員','打球'),(302,'布蘭登','123456','	[email protected]','MyBatis團隊成員','聽歌'),(303,'亞當','123456','[email protected]','MyBatis團隊貢獻者','游泳');

/*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','看起來不錯!謝謝@ 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','弗蘭克·馬丁內斯','弗蘭克','馬丁內斯','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,'以下是用戶可見更改的列表。用參數名稱指定的keyProperty可能導致ExecutorException。#1485'),(502,102,302,'2020-02-02','2','MyBatis 3.5.2',1,'以下是用戶可見更改的列表。SQL Builder現在支持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,'以下是用戶可見更改的列表。用參數名稱指定的keyProperty可能導致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','[email protected]'),(403,'guest','123456','[email protected]'),(411,'test','123456','[email protected]'),(412,'test2','123456','[email protected]');

/*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創建Maven項目

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

	<!-- 設置(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>

	<!-- 環境配置(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>

	<!-- 數據庫廠商標識(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
# 控制檯輸出
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:創建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 大強
 *
 */
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創建SqlSessionFactory
			sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 由 SqlSessionFactory創建SqlSession
	 * 
	 * @return
	 */
	public static SqlSession getSqlSession() {
		return sqlSessionFactory.openSession();
	}

	/**
	 * 關閉SqlSession
	 * 
	 * @param sqlSession
	 */
	public static void closeSqlSession(SqlSession sqlSession) {
		if (sqlSession != null) {
			sqlSession.close();
		}
	}

}

步驟 5:創建POJO類

package org.mybatis.example.domain;

/**
 * 作者POJO類
 * 
 * @author 大強
 *
 */
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 大強
 *
 */
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 大強
 *
 */
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;

/**
 * 評論POJO類
 * 
 * @author 大強
 *
 */
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 大強
 *
 */
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 大強
 *
 */
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 大強
 *
 */
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;

/**
 * 標籤POJO類
 * 
 * @author 大強
 *
 */
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 大強
 *
 */
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 大強
 *
 */
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 大強
 *
 */
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:創建映射器接口類

package org.mybatis.example.mapper;

import java.util.List;

import org.mybatis.example.domain.Blog;

/**
 * 博客映射器
 * 
 * @author 大強
 *
 */
public interface BlogMapper {

	List<Blog> selectBlogDetails(int id);

}

步驟 7:創建映射器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">

	<!-- 非常複雜的語句 -->
	<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 大強
 *
 */
public class BlogMapperTest {

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

	// 注意:選中方法名,單擊鼠標右鍵,選擇 Run as -> JUnit Test,就能執行單個方法。

	/**
	 * 非常複雜的結果映射測試方法
	 */
	@Test
	public void detailedBlogResultMapTest() {
		logger.info("非常複雜的結果映射開始...");
		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("非常複雜的結果映射結束");
	}

}

如有疑問,請看視頻教程:https://edu.csdn.net/course/detail/28508

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章