步骤 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,'以下是用户可见更改的列表。在包含的
/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项目
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">;
org.mybatis
mybatis
3.5.4
mysql
mysql-connector-java
5.1.48
log4j
log4j
1.2.17
junit
junit
4.12
步骤 3:配置MyBatis
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/mybatis
username=root
password_dev=123456
password_pro=12345678
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">;
全局日志配置
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 Listposts; 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
getPosts() {
return posts;
}public void setPosts(List
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
comments; public List
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
getComments() {
return comments;
}public void setComments(List
comments) {
this.comments = comments;
}public List
getTags() {
return tags;
}public void setTags(List
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
selectBlogDetails(int id);
}
步骤 7:创建映射器XML文件
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">;
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,就能执行单个方法。
/**
- 非常复杂的结果映射测试方法br/>*/
@Test
public void detailedBlogResultMapTest() {
logger.info("非常复杂的结果映射开始...");
SqlSession session = MyBatisUtil.getSqlSession();
BlogMapper mapper = session.getMapper(BlogMapper.class);
Listlist = mapper.selectBlogDetails(101);
if (list != null) {
for (Blog blog : list) {
logger.info(blog.getId());
logger.info(blog.getTitle());
}
}
MyBatisUtil.closeSqlSession(session);
logger.info("非常复杂的结果映射结束");
}
- 非常复杂的结果映射测试方法br/>*/
}