一、创建数据库表1.1、创建数据表同时插入数据
/*SQLyog EnterPRise v12.09 (64 bit)MySQL- 5.6.27-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*/;CREATEDATABASE/*!32312 IF NOT EXISTS*/`mybatis`/*!40100 DEFAULT CHARACTER SET utf8*/;USE`mybatis`;/*Table structure for table `author`*/DROPTABLEIFEXISTS`author`;CREATETABLE`author` (
`author_id`int(11) unsignedNOTNULLAUTO_INCREMENT COMMENT'作者ID主键',
`author_username`varchar(30)NOTNULLCOMMENT'作者用户名',
`author_passWord`varchar(32)NOTNULLCOMMENT'作者密码',
`author_email`varchar(50)NOTNULLCOMMENT'作者邮箱',
`author_bio`varchar(1000)DEFAULT'这家伙很赖,什么也没留下'COMMENT'作者简介',
`register_time`datetimeDEFAULTCURRENT_TIMESTAMPCOMMENT'注册时间',PRIMARYKEY(`author_id`)
) ENGINE=InnoDB AUTO_INCREMENT=6DEFAULTCHARSET=utf8;/*Data for the table `author`*/
insert into `author`(`author_id`,`author_username`,`author_password`,`author_email`,`author_bio`,`register_time`) values (1,'张三','123456','123@QQ.com','张三是个新手,刚开始注册','2015-10-29 10:23:59'),(2,'李四','123asf','lisi@163.com','魂牵梦萦 ','2015-10-29 10:24:29'),(3,'王五','dfsd342','ww@sina.com','康熙王朝','2015-10-29 10:25:23'),(4,'赵六','123098sdfa','zhaoliu@qq.com','花午骨','2015-10-29 10:26:09'),(5,'钱七','zxasqw','qianqi@qq.com','这家伙很赖,什么也没留下','2015-10-29 10:27:04'),(6,'张三丰','123456','zhangsf@qq.com','这家伙很赖,什么也没留下','2015-10-29 11:48:00'),(7,'张无忌','qwertyuiop','wuji@163.com','这家伙很赖,什么也没留下','2015-10-29 11:48:24');
/*Table structure for table `blog`*/DROPTABLEIFEXISTS`blog`;CREATETABLE`blog` (
`blog_id`int(11) unsignedNOTNULLAUTO_INCREMENT COMMENT'BlogId主键',
`blog_title`varchar(255)NOTNULLCOMMENT'blog标题',
`author_id`int(11) unsignedNOTNULLCOMMENT'作者ID外键',PRIMARYKEY(`blog_id`),KEY`fk_author_id` (`author_id`),CONSTRAINT`fk_author_id`FOREIGNKEY(`author_id`)REFERENCES`author` (`author_id`)
) ENGINE=InnoDB AUTO_INCREMENT=6DEFAULTCHARSET=utf8;/*Data for the table `blog`*/insertinto`blog`(`blog_id`,`blog_title`,`author_id`)values(1,'小张的Blog',1),(2,'小李',2),(3,'王五不是人',3),(4,'赵地人',4),(5,'钱钱钱',5);/*Table structure for table `posts`*/DROPTABLEIFEXISTS`posts`;CREATETABLE`posts` (
`post_id`int(11) unsignedNOTNULLAUTO_INCREMENT COMMENT'文章主键ID',
`post_subject`varchar(255)NOTNULLCOMMENT'文章主题,标题',
`post_body`textNOTNULLCOMMENT'文章内容最大3000个字符',
`blog_id`int(11) unsignedNOTNULLCOMMENT'Blog主键做外键',
`createtime`datetimeDEFAULTCURRENT_TIMESTAMPCOMMENT'文章创建时间',PRIMARYKEY(`post_id`),KEY`fk_blog_id` (`blog_id`),CONSTRAINT`fk_blog_id`FOREIGNKEY(`blog_id`)REFERENCES`blog` (`blog_id`)
) ENGINE=InnoDB AUTO_INCREMENT=8DEFAULTCHARSET=utf8mb4;/*Data for the table `posts`*/insertinto`posts`(`post_id`,`post_subject`,`post_body`,`blog_id`,`createtime`)values(1,'Mybatis入门一','什么是 MyBatis ?\r\nMyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的持久层框架。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以对配置和原生Map使用简单的xml或注解,将接口和java的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。',1,'2015-10-29 10:32:21'),(2,'Mybatis入门二','要使用 MyBatis, 只需将 mybatis-x.x.x.jar 文件置于 classpath 中即可。',1,'2015-10-29 10:32:52'),(3,'Oracle学习','Oracle Database,又名Oracle RDBMS,或简称Oracle。是甲骨文公司的一款关系数据库管理系统',2,'2015-10-29 10:33:26'),(4,'JAVA学习一','Java是由Sun Microsystems公司于1995年5月推出的Java面向对象程序设计语言和Java平台的总称',3,'2015-10-29 10:34:17'),(5,'PL/SQL','PL/SQL也是一种程序语言,叫做过程化SQL语言(Procedural Language/SQL)。PL/SQL是Oracle数据库对SQL语句的扩展',4,'2015-10-29 10:37:52'),(6,'CSS标签选择器','标签选择器\r\nID选择器\r\n类选择器\r\n特殊选择器',5,'2015-10-29 10:39:44'),(7,'javascript','js:是前端脚本语言',2,'2015-10-29 10:40:18');/*!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.1、创建项目并加入jar包
2.2、创建实体类以author为例
packagecom.pb.mybatis.po;importjava.util.Date;/***
* @Title: Author.java
* @Package com.pb.mybatis.po
* @ClassName Author
* @Description: TODO(Blog作者类)
*@author刘楠
* @date 2015-10-29 上午9:27:53
*@versionV1.0*/publicclassAuthor {//作者IDprivateintauthorId;//作者用户名privateString authorUserName;//作者密码privateString authorPassword;//作者邮箱privateString authorEmail;//作者介绍privateintauthorBio;//注册时间privateDate registerTime;/***@returnthe authorId*/publicintgetAuthorId() {returnauthorId;
}/***@paramauthorId the authorId to set*/publicvoidsetAuthorId(intauthorId) {this.authorId =authorId;
}/***@returnthe authorUserName*/publicString getAuthorUserName() {returnauthorUserName;
}/***@paramauthorUserName the authorUserName to set*/publicvoidsetAuthorUserName(String authorUserName) {this.authorUserName =authorUserName;
}/***@returnthe authorPassword*/publicString getAuthorPassword() {returnauthorPassword;
}/***@paramauthorPassword the authorPassword to set*/publicvoidsetAuthorPassword(String authorPassword) {this.authorPassword =authorPassword;
}/***@returnthe authorEmail*/publicString getAuthorEmail() {returnauthorEmail;
}/***@paramauthorEmail the authorEmail to set*/publicvoidsetAuthorEmail(String authorEmail) {this.authorEmail =authorEmail;
}/***@returnthe authorBio*/publicintgetAuthorBio() {returnauthorBio;
}/***@paramauthorBio the authorBio to set*/publicvoidsetAuthorBio(intauthorBio) {this.authorBio =authorBio;
}/***@returnthe registerTime*/publicDate getRegisterTime() {returnregisterTime;
}/***@paramregisterTime the registerTime to set*/publicvoidsetRegisterTime(Date registerTime) {this.registerTime =registerTime;
}/**(non Javadoc)
* <p>Title: toString</p>
* <p>Description:重写toString方法 </p>
*@return*@seejava.lang.Object#toString()*/@OverridepublicString toString() {return"Author [authorId=" + authorId + ", authorUserName="
+ authorUserName + ", authorPassword=" +authorPassword+ ", authorEmail=" + authorEmail + ", authorBio=" +authorBio+ ", registerTime=" + registerTime + "]";
}
}
2.3、创建mybatis配置文件
<?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><propertiesresource="db.properties"/><typeAliases><!--使用默认别名--><packagename="com.pb.mybatis.po"/></typeAliases><environmentsdefault="development"><environmentid="development"><transactionManagertype="JDBC"/><dataSourcetype="POOLED"><propertyname="driver"value="${jdbc.driver}"/><propertyname="url"value="${jdbc.url}"/><propertyname="username"value="${jdbc.username}"/><propertyname="password"value="${jdbc.password}"/></dataSource></environment></environments><mappers><!--加载映射--><packagename="com.pb.mybatis.mapper"/></mappers></configuration>
2.4、创建实体类对象的接口以author为例
/***/packagecom.pb.mybatis.mapper;importjava.util.List;importcom.pb.mybatis.po.Author;/*** @Title: AuthorMapper.java
* @Package com.pb.mybatis.mapper
* @ClassName AuthorMapper
* @Description: TODO(作者接口)
*@author刘楠
* @date 2015-10-29 上午11:13:10
*@versionV1.0*/publicinterfaceAuthorMapper {/***
* @Title: findById
* @Description: TODO(根据查找一个用户)
*@paramid
*@returnAuthor*/publicAuthor findAuthorById(intauthorId);/***
* @Title: findByName
* @Description: TODO(根据用户名,模糊查询)
*@paramname
*@returnList<Author>*/publicList<Author>findAuthorByName(String name);/***
* @Title: addAuthor
* @Description: TODO(添加作者)
*@paramauthor
*@returnint*/publicintaddAuthor(Author author);/***
* @Title: updateAuthor
* @Description: TODO(修改用户)
*@paramauthro
*@returnint*/publicintupdateAuthor(Author authro);/***
* @Title: deleteAturho
* @Description: TODO(根据ID删除作者)
*@paramid
*@returnint*/publicintdeleteAuthor(intauthorId);
}
2.5、创建接口对应的mapper.xm以author为例
<?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"><mappernamespace="com.pb.mybatis.mapper.AuthorMapper"><!--使用resultMap映射 type使用别名,--><resultMaptype="Author"id="authorResultMap"><!--主键--><idproperty="authorId"column="author_id"/><!--普通属性与表中的字段对应--><resultproperty="authorUserName"column="author_username"/><resultproperty="authorPassword"column="author_password"/><resultproperty="authorEmail"column="author_email"/><resultproperty="authorBio"column="author_bio"/><resultproperty="registerTime"column="register_time"/></resultMap><!--根据查找一个用户--><selectid="findAuthorById"parameterType="int"resultMap="authorResultMap">SELECT * FROM author
WHERE author_id=#{authorId}</select><!--根据用户名,模糊查询--><selectid="findAuthorByName"parameterType="String"resultMap="authorResultMap">SELECT * FROM author
WHERE author_username LIKE "%"#{name}"%"</select><!--添加用户
useGeneratedKeys="true" 使用数据库自增序列
keyProperty="authorId"将主键返回
#号中写PO类中的属性--><insertid="addAuthor"parameterType="Author"useGeneratedKeys="true"keyProperty="authorId">INSERT INTO author(author_username,author_password,author_email,author_bio,register_time)
VALUES(#{authorUserName},#{authorPassword},#{authorEmail},#{authorBio},#{registerTime})</insert><!--修改用户--><updateid="updateAuthor"parameterType="Author">update author
set
author_username=#{authorUserName},
author_password=#{authorPassword},
author_email=#{authorEmail},
author_bio=#{authorBio},
register_time=#{registerTime}
where author_id=#{authorId}</update><!--删除用户 根据ID--><deleteid="deleteAuthor"parameterType="int">delete from author
where author_id=#{authorId}</delete></mapper>
三、简单实现增删改查
3.1、测试类以author为例
/***/packagecom.pb.mybatis.mapper;importjava.io.InputStream;importjava.util.Date;importjava.util.List;importorg.apache.ibatis.io.Resources;importorg.apache.ibatis.session.SqlSession;importorg.apache.ibatis.session.SqlSessionFactory;importorg.apache.ibatis.session.SqlSessionFactoryBuilder;importorg.junit.Before;importorg.junit.Test;importcom.pb.mybatis.po.Author;/*** @Title: AuthorMapperTest.java
* @Package com.pb.mybatis.mapper
* @ClassName AuthorMapperTest
* @Description: TODO(测试)
*@author刘楠
* @date 2015-10-29 上午11:57:21
*@versionV1.0*/publicclassAuthorMapperTest {privateSqlSessionFactory sqlSessionFactory;/***
* @Title: setUp
* @Description: TODO(在每个方法前执行的方法)
*@throwsException void*/@BeforepublicvoidsetUp()throwsException {
String resource="configuration.xml";
InputStream in=Resources.getResourceAsStream(resource);//获取会话工厂sqlSessionFactory=newSqlSessionFactoryBuilder().build(in);
}/***
* @Title: testFindAuthorById
* @Description: TODO(根据查找一个用户)
void*/@TestpublicvoidtestFindAuthorById() {//获取会话SqlSession sqlSession=sqlSessionFactory.openSession();//Mapper接口AuthorMapper authorMapper=sqlSession.getMapper(AuthorMapper.class);//调用方法Author author=authorMapper.findAuthorById(2);
System.out.println(author);//关闭会话sqlSession.close();
}/***
* @Title: testFindAuthorByName
* @Description: TODO(根据用户名,模糊查询)
void*/@TestpublicvoidtestFindAuthorByName() {//获取会话SqlSession sqlSession=sqlSessionFactory.openSession();//Mapper接口AuthorMapper authorMapper=sqlSession.getMapper(AuthorMapper.class);//调用方法List<Author> authors=authorMapper.findAuthorByName("张");
System.out.println(authors);//关闭会话sqlSession.close();for(Author a:authors){
System.out.println(a.toString());
}
}/***
* @Title: testAddAuthor
* @Description: TODO(添加作者)
void*/@TestpublicvoidtestAddAuthor() {//获取会话SqlSession sqlSession=sqlSessionFactory.openSession();//Mapper接口AuthorMapper authorMapper=sqlSession.getMapper(AuthorMapper.class);//调用方法Author author=newAuthor();
author.setAuthorUserName("不知道");
author.setAuthorPassword("1234567890");
author.setAuthorEmail("123456@qq.com");
author.setAuthorBio("知道是个什么");
author.setRegisterTime(newDate());intnum=authorMapper.addAuthor(author);
System.out.println("num="+num);
System.out.println("authorId="+author.getAuthorId());
sqlSession.commit();//关闭会话sqlSession.close();
}/***
* @Title: testUpdateAuthor
* @Description: TODO(修改用户)
void*/@TestpublicvoidtestUpdateAuthor() {//获取会话SqlSession sqlSession=sqlSessionFactory.openSession();//Mapper接口AuthorMapper authorMapper=sqlSession.getMapper(AuthorMapper.class);//调用方法Author author=authorMapper.findAuthorById(8);
author.setAuthorUserName("知道了");
author.setAuthorPassword("456789");
author.setAuthorEmail("456789@qq.com");
author.setAuthorBio("哈哈哈哈哈雅虎");
author.setRegisterTime(newDate());intnum=authorMapper.updateAuthor(author);
System.out.println("num="+num);
System.out.println("authorId="+author.getAuthorId());
sqlSession.commit();//关闭会话sqlSession.close();
}/***
* @Title: testDeleteAuthor
* @Description: TODO(根据ID删除作者)
void*/@TestpublicvoidtestDeleteAuthor() {//获取会话SqlSession sqlSession=sqlSessionFactory.openSession();//Mapper接口AuthorMapper authorMapper=sqlSession.getMapper(AuthorMapper.class);//调用方法intnum=authorMapper.deleteAuthor(10);
System.out.println("num="+num);
sqlSession.commit();//关闭会话sqlSession.close();
}
}
四、实现一对一4.1、建立Blog类
packagecom.pb.mybatis.po;/*** @Title: Blog.java
* @Package com.pb.mybatis.po
* @ClassName Blog
* @Description: TODO(博客)
*@author刘楠
* @date 2015-10-29 上午9:32:56
*@versionV1.0*/publicclassBlog {//博客IDprivateintblogId;//标题privateString blogTitle;//博客作者privateAuthor author;/***@returnthe blogId*/publicintgetBlogId() {returnblogId;
}/***@paramblogId the blogId to set*/publicvoidsetBlogId(intblogId) {this.blogId =blogId;
}/***@returnthe blogTitle*/publicString getBlogTitle() {returnblogTitle;
}/***@paramblogTitle the blogTitle to set*/publicvoidsetBlogTitle(String blogTitle) {this.blogTitle =blogTitle;
}/***@returnthe author*/publicAuthor getAuthor() {returnauthor;
}/***@paramauthor the author to set*/publicvoidsetAuthor(Author author) {this.author =author;
}/**(non Javadoc)
* <p>Title: toString</p>
* <p>Description: 重写toString方法</p>
*@return*@seejava.lang.Object#toString()*/@OverridepublicString toString() {return"Blog [blogId=" + blogId + ", blogTitle=" +blogTitle+ ", author=" + author + "]";
}
}
4.2、建立BlogMapper接口
/***/packagecom.pb.mybatis.mapper;importjava.util.List;importcom.pb.mybatis.po.Author;importcom.pb.mybatis.po.Blog;/*** @Title: BlogMapper.java
* @Package com.pb.mybatis.mapper
* @ClassName BlogMapper
* @Description: TODO(用一句话描述该文件做什么)
*@author刘楠
* @date 2015-10-29 上午11:13:21
*@versionV1.0*/publicinterfaceBlogMapper {/***
* @Title: findBlogById
* @Description: TODO(根据ID查找BLOG)
*@paramid
*@returnBlog*/publicBlog findBlogById(intid);/***
* @Title: findByName
* @Description: TODO(根据博客名查找)
*@paramname
*@returnList<Blog>*/publicList<Blog>findBlogByName(String blogTitle);/***
* @Title: addBlog
* @Description: TODO(添加博客)
*@paramblog
*@returnint*/publicintaddBlog(Blog blog);/***
* @Title: updateBlog
* @Description: TODO(修改博客)
*@paramblog
*@returnint*/publicintupdateBlog(Blog blog);/***
* @Title: deleteBlog
* @Description: TODO(删除博客)
*@paramid
*@returnint*/publicintdeleteBlog(intid);
}
4.3、建立mapper.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"><mappernamespace="com.pb.mybatis.mapper.BlogMapper"><!--使用ResultMap--><resultMaptype="Blog"id="blogResultMap"><!--主键--><idproperty="blogId"column="blog_id"/><!--标题--><resultproperty="blogTitle"column="blog_title"/><!--一对一关联 第一种--><associationproperty="author"resultMap="authorResultMap"/><!--第二种
把作者类再映射在一个resultMap中
<association property="author" resultMap="authorResultMap">
<id property="authorId" column="author_id"/>
普通属性与表中的字段对应
<result property="authorUserName" column="author_username"/>
<result property="authorPassword" column="author_password"/>
<result property="authorEmail" column="author_email"/>
<result property="authorBio" column="author_bio"/>
<result property="registerTime" column="register_time"/>
</association>--></resultMap><!--使用resultMap映射 type使用别名,单独使用Author关联--><resultMaptype="Author"id="authorResultMap"><!--主键--><idproperty="authorId"column="author_id"/><!--普通属性与表中的字段对应--><resultproperty="authorUserName"column="author_username"/><resultproperty="authorPassword"column="author_password"/><resultproperty="authorEmail"column="author_email"/><resultproperty="authorBio"column="author_bio"/><resultproperty="registerTime"column="register_time"/></resultMap><!--根据ID查询--><selectid="findBlogById"parameterType="int"resultMap="blogResultMap">SELECT blog.blog_id,blog.blog_title,author.author_id,author.author_username,author.author_password,author.author_email,author.author_bio,author.register_time
FROM blog,author
WHERE blog.author_id=author.author_id
AND blog.blog_id=#{blogId}</select><!--根据名字查询--><selectid="findBlogByName"parameterType="String"resultMap="blogResultMap">SELECT blog.blog_id,blog.blog_title,author.author_id,author.author_username,author.author_password,author.author_email,author.author_bio,author.register_time
FROM blog,author
WHERE blog.author_id=author.author_id
AND blog_title LIKE "%"#{blogTitle}"%"</select><!--添加Blog--><insertid="addBlog"parameterType="Blog"useGeneratedKeys="true"keyProperty="blogId">INSERT INTO blog(blog_title,author_id)
VALUES(#{blogTitle},#{author.authorId})</insert><!--修改--><updateid="updateBlog"parameterType="Blog">UPDATE blog
SET blog_title=#{blogTitle},
author_id=#{author.authorId}
WHERE blog_id=#{blogId}</update><!--删除--><deleteid="deleteBlog"parameterType="int">delete from blog where blog_id=#{blogId}</delete></mapper>
4.1、测试类
packagecom.pb.mybatis.mapper;importstaticorg.junit.Assert.*;importjava.io.InputStream;importjava.util.List;importorg.apache.ibatis.io.Resources;importorg.apache.ibatis.session.SqlSession;importorg.apache.ibatis.session.SqlSessionFactory;importorg.apache.ibatis.session.SqlSessionFactoryBuilder;importorg.junit.Before;importorg.junit.Test;importcom.pb.mybatis.po.Author;importcom.pb.mybatis.po.Blog;/*** @Title: BlogMapperTest.java
* @Package com.pb.mybatis.mapper
* @ClassName BlogMapperTest
* @Description: TODO(用一句话描述该文件做什么)
*@author刘楠
* @date 2015-10-29 下午3:12:52
*@versionV1.0*/publicclassBlogMapperTest {privateSqlSessionFactory sqlSessionFactory;
@BeforepublicvoidsetUp()throwsException {
String resource="configuration.xml";
InputStream in=Resources.getResourceAsStream(resource);//获取会话工厂sqlSessionFactory=newSqlSessionFactoryBuilder().build(in);
}/*** Test method for {@linkcom.pb.mybatis.mapper.BlogMapper#findBlogById(int)}.*/@TestpublicvoidtestFindBlogById() {//获取会话SqlSession sqlSession=sqlSessionFactory.openSession();//Mapper接口BlogMapper blogMapper=sqlSession.getMapper(BlogMapper.class);//调用方法Blog blog=blogMapper.findBlogById(2);
System.out.println(blog);//关闭会话sqlSession.close();
}/*** Test method for {@linkcom.pb.mybatis.mapper.BlogMapper#findBlogByName(java.lang.String)}.*/@TestpublicvoidtestFindBlogByName() {//获取会话SqlSession sqlSession=sqlSessionFactory.openSession();//Mapper接口BlogMapper blogMapper=sqlSession.getMapper(BlogMapper.class);//调用方法List<Blog> blogs=blogMapper.findBlogByName("小");
System.out.println(blogs);//关闭会话sqlSession.close();
}/*** Test method for {@linkcom.pb.mybatis.mapper.BlogMapper#addBlog(com.pb.mybatis.po.Blog)}.*/@TestpublicvoidtestAddBlog() {//获取会话SqlSession sqlSession=sqlSessionFactory.openSession();//Mapper接口BlogMapper blogMapper=sqlSession.getMapper(BlogMapper.class);
Blog blog=newBlog();
blog.setBlogTitle("倚天屠龙记");
AuthorMapper authorMapper=sqlSession.getMapper(AuthorMapper.class);//调用方法Author author=authorMapper.findAuthorById(2);
blog.setAuthor(author);intnum=blogMapper.addBlog(blog);
System.out.println("num="+num);
System.out.println(blog.getBlogId());
sqlSession.commit();
sqlSession.close();
}/*** Test method for {@linkcom.pb.mybatis.mapper.BlogMapper#updateBlog(com.pb.mybatis.po.Blog)}.*/@TestpublicvoidtestUpdateBlog() {//获取会话SqlSession sqlSession=sqlSessionFactory.openSession();//Mapper接口BlogMapper blogMapper=sqlSession.getMapper(BlogMapper.class);//调用方法Blog blog=blogMapper.findBlogById(8);
blog.setBlogTitle("笑傲江湖");
Author author=blog.getAuthor();
author.setAuthorUserName("金庸");
AuthorMapper authorMapper=sqlSession.getMapper(AuthorMapper.class);intauthorNum=authorMapper.updateAuthor(author);intnum=blogMapper.updateBlog(blog);
System.out.println("authorNum="+authorNum);
System.out.println("num="+num);
sqlSession.commit();//关闭会话sqlSession.close();
}/*** Test method for {@linkcom.pb.mybatis.mapper.BlogMapper#deleteBlog(int)}.*/@TestpublicvoidtestDeleteBlog() {//获取会话SqlSession sqlSession=sqlSessionFactory.openSession();//Mapper接口BlogMapper blogMapper=sqlSession.getMapper(BlogMapper.class);intnum=blogMapper.deleteBlog(11);
System.out.println("num="+num);
sqlSession.commit();
sqlSession.close();
}
}
五、一对多
5.1、建立Posts类
packagecom.pb.mybatis.po;importjava.util.Date;/*** @Title: Posts.java
* @Package com.pb.mybatis.po
* @ClassName Posts
* @Description: TODO(Blog文章)
*@author刘楠
* @date 2015-10-29 上午9:31:22
*@versionV1.0*/publicclassPosts {//文章IDprivateintpostId;//文件主题privateString postSubject;//主体内容privateString postBody;//文章建立时间privateDate createTime;/***@returnthe postId*/publicintgetPostId() {returnpostId;
}/***@parampostId the postId to set*/publicvoidsetPostId(intpostId) {this.postId =postId;
}/***@returnthe postSubject*/publicString getPostSubject() {returnpostSubject;
}/***@parampostSubject the postSubject to set*/publicvoidsetPostSubject(String postSubject) {this.postSubject =postSubject;
}/***@returnthe postBody*/publicString getPostBody() {returnpostBody;
}/***@parampostBody the postBody to set*/publicvoidsetPostBody(String postBody) {this.postBody =postBody;
}/***@returnthe createTime*/publicDate getCreateTime() {returncreateTime;
}/***@paramcreateTime the createTime to set*/publicvoidsetCreateTime(Date createTime) {this.createTime =createTime;
}/**(non Javadoc)
* <p>Title: toString</p>
* <p>Description:重写toString方法</p>
*@return*@seejava.lang.Object#toString()*/@OverridepublicString toString() {return"Posts [postId=" + postId + ", postSubject=" +postSubject+ ", postBody=" + postBody +", createTime="
+ createTime + "]";
}
}
5.2、在blog类中添加List
packagecom.pb.mybatis.po;importjava.util.List;/*** @Title: Blog.java
* @Package com.pb.mybatis.po
* @ClassName Blog
* @Description: TODO(博客)
*@author刘楠
* @date 2015-10-29 上午9:32:56
*@versionV1.0*/publicclassBlog {//博客IDprivateintblogId;//标题privateString blogTitle;//博客作者privateAuthor author;//文章ListprivateList<Posts>posts;/***@returnthe blogId*/publicintgetBlogId() {returnblogId;
}/***@paramblogId the blogId to set*/publicvoidsetBlogId(intblogId) {this.blogId =blogId;
}/***@returnthe blogTitle*/publicString getBlogTitle() {returnblogTitle;
}/***@paramblogTitle the blogTitle to set*/publicvoidsetBlogTitle(String blogTitle) {this.blogTitle =blogTitle;
}/***@returnthe author*/publicAuthor getAuthor() {returnauthor;
}/***@paramauthor the author to set*/publicvoidsetAuthor(Author author) {this.author =author;
}/***@returnthe posts*/publicList<Posts>getPosts() {returnposts;
}/***@paramposts the posts to set*/publicvoidsetPosts(List<Posts>posts) {this.posts =posts;
}/**(non Javadoc)
* <p>Title: toString</p>
* <p>Description: </p>
*@return*@seejava.lang.Object#toString()*/@OverridepublicString toString() {return"Blog [blogId=" + blogId + ", blogTitle=" +blogTitle+ ", author=" + author + ", posts=" + posts + "]";
}
}
5.3、修改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"><mappernamespace="com.pb.mybatis.mapper.BlogMapper"><!--使用ResultMap--><resultMaptype="Blog"id="blogResultMap"><!--主键--><idproperty="blogId"column="blog_id"/><!--标题--><resultproperty="blogTitle"column="blog_title"/><!--一对一关联 第一种--><associationproperty="author"resultMap="authorResultMap"/><!--一对多关联--><collectionproperty="posts"resultMap="postsResultMap"ofType="Posts"/><!--第二种
把作者类再映射在一个resultMap中
<association property="author" resultMap="authorResultMap">
<id property="authorId" column="author_id"/>
普通属性与表中的字段对应
<result property="authorUserName" column="author_username"/>
<result property="authorPassword" column="author_password"/>
<result property="authorEmail" column="author_email"/>
<result property="authorBio" column="author_bio"/>
<result property="registerTime" column="register_time"/>
</association>--></resultMap><!--文章Map--><resultMaptype="Posts"id="postsResultMap"><idproperty="postId"column="post_id"/><resultproperty="postSubject"column="post_subject"/><resultproperty="postBody"column="post_body"/><resultproperty="createTime"column="createtime"/></resultMap><!--使用resultMap映射 type使用别名,单独使用Author关联--><resultMaptype="Author"id="authorResultMap"><!--主键--><idproperty="authorId"column="author_id"/><!--普通属性与表中的字段对应--><resultproperty="authorUserName"column="author_username"/><resultproperty="authorPassword"column="author_password"/><resultproperty="authorEmail"column="author_email"/><resultproperty="authorBio"column="author_bio"/><resultproperty="registerTime"column="register_time"/></resultMap><!--根据ID查询--><selectid="findBlogById"parameterType="int"resultMap="blogResultMap">SELECT blog.blog_id,blog.blog_title,
author.author_id,author.author_username,author.author_password,author.author_email,author.author_bio,author.register_time,
posts.post_id,posts.post_subject,posts.post_body,posts.createtime,posts.blog_id
FROM blog,author,posts
WHERE blog.author_id=author.author_id
AND blog.blog_id=posts.blog_id
AND blog.blog_id=#{blogId}</select><!--根据名字查询--><selectid="findBlogByName"parameterType="String"resultMap="blogResultMap">SELECT blog.blog_id,blog.blog_title,author.author_id,author.author_username,author.author_password,author.author_email,author.author_bio,author.register_time
FROM blog,author
WHERE blog.author_id=author.author_id
AND blog_title LIKE "%"#{blogTitle}"%"</select><!--添加Blog--><insertid="addBlog"parameterType="Blog"useGeneratedKeys="true"keyProperty="blogId">INSERT INTO blog(blog_title,author_id)
VALUES(#{blogTitle},#{author.authorId})</insert><!--修改--><updateid="updateBlog"parameterType="Blog">UPDATE blog
SET blog_title=#{blogTitle},
author_id=#{author.authorId}
WHERE blog_id=#{blogId}</update><!--删除--><deleteid="deleteBlog"parameterType="int">delete from blog where blog_id=#{blogId}</delete></mapper>
5.4、测试
测试类不变