MyBatis入门(二)---一对一,一对多

一、创建数据库表

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 */;
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` (`author_id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '作者ID主键',`author_username` varchar(30) NOT NULL COMMENT '作者用户名',`author_password` varchar(32) NOT NULL COMMENT '作者密码',`author_email` varchar(50) NOT NULL COMMENT '作者邮箱',`author_bio` varchar(1000) DEFAULT '这家伙很赖,什么也没留下' COMMENT '作者简介',`register_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '注册时间',PRIMARY KEY (`author_id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=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` */DROP TABLE IF EXISTS `blog`;CREATE TABLE `blog` (`blog_id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT 'BlogId主键',`blog_title` varchar(255) NOT NULL COMMENT 'blog标题',`author_id` int(11) unsigned NOT NULL COMMENT '作者ID外键',PRIMARY KEY (`blog_id`),KEY `fk_author_id` (`author_id`),CONSTRAINT `fk_author_id` FOREIGN KEY (`author_id`) REFERENCES `author` (`author_id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;/*Data for the table `blog` */insert  into `blog`(`blog_id`,`blog_title`,`author_id`) values (1,'小张的Blog',1),(2,'小李',2),(3,'王五不是人',3),(4,'赵地人',4),(5,'钱钱钱',5);/*Table structure for table `posts` */DROP TABLE IF EXISTS `posts`;CREATE TABLE `posts` (`post_id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '文章主键ID',`post_subject` varchar(255) NOT NULL COMMENT '文章主题,标题',`post_body` text NOT NULL COMMENT '文章内容最大3000个字符',`blog_id` int(11) unsigned NOT NULL COMMENT 'Blog主键做外键',`createtime` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '文章创建时间',PRIMARY KEY (`post_id`),KEY `fk_blog_id` (`blog_id`),CONSTRAINT `fk_blog_id` FOREIGN KEY (`blog_id`) REFERENCES `blog` (`blog_id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8mb4;/*Data for the table `posts` */insert  into `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为例

 

package com.pb.mybatis.po;import java.util.Date;/*** * @Title: Author.java* @Package com.pb.mybatis.po* @ClassName Author* @Description: TODO(Blog作者类)* @author 刘楠 * @date 2015-10-29 上午9:27:53* @version V1.0*/
public class Author {//作者IDprivate int authorId;//作者用户名private String authorUserName;//作者密码private String authorPassword;//作者邮箱private String authorEmail;//作者介绍private int authorBio;//注册时间private Date registerTime;/*** @return the authorId*/public int getAuthorId() {return authorId;}/*** @param authorId the authorId to set*/public void setAuthorId(int authorId) {this.authorId = authorId;}/*** @return the authorUserName*/public String getAuthorUserName() {return authorUserName;}/*** @param authorUserName the authorUserName to set*/public void setAuthorUserName(String authorUserName) {this.authorUserName = authorUserName;}/*** @return the authorPassword*/public String getAuthorPassword() {return authorPassword;}/*** @param authorPassword the authorPassword to set*/public void setAuthorPassword(String authorPassword) {this.authorPassword = authorPassword;}/*** @return the authorEmail*/public String getAuthorEmail() {return authorEmail;}/*** @param authorEmail the authorEmail to set*/public void setAuthorEmail(String authorEmail) {this.authorEmail = authorEmail;}/*** @return the authorBio*/public int getAuthorBio() {return authorBio;}/*** @param authorBio the authorBio to set*/public void setAuthorBio(int authorBio) {this.authorBio = authorBio;}/*** @return the registerTime*/public Date getRegisterTime() {return registerTime;}/*** @param registerTime the registerTime to set*/public void setRegisterTime(Date registerTime) {this.registerTime = registerTime;}/** (non Javadoc)* <p>Title: toString</p>* <p>Description:重写toString方法 </p>* @return* @see java.lang.Object#toString()*/@Overridepublic String 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 configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration>
<properties resource="db.properties" />
<typeAliases>
<!--使用默认别名  -->
<package name="com.pb.mybatis.po"/>
</typeAliases>
<environments default="development">
<environment id="development"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver" value="${jdbc.driver}"/><property name="url" value="${jdbc.url}"/><property name="username" value="${jdbc.username}"/><property name="password" value="${jdbc.password}"/></dataSource>
</environment>
</environments>
<mappers>
<!-- 加载映射 --><package name="com.pb.mybatis.mapper"/>
</mappers>
</configuration>

 

2.4、创建实体类对象的接口以author为例

 

/**
*/
package com.pb.mybatis.mapper;import java.util.List;import com.pb.mybatis.po.Author;/**  * @Title: AuthorMapper.java* @Package com.pb.mybatis.mapper* @ClassName AuthorMapper* @Description: TODO(作者接口)* @author 刘楠 * @date 2015-10-29 上午11:13:10* @version V1.0  */
public interface AuthorMapper {/*** * @Title: findById* @Description: TODO(根据查找一个用户)* @param id* @return Author*/public Author findAuthorById(int authorId);/*** * @Title: findByName* @Description: TODO(根据用户名,模糊查询)* @param name* @return List<Author>*/public List<Author> findAuthorByName(String name);/*** * @Title: addAuthor* @Description: TODO(添加作者)* @param author* @return int*/public int addAuthor(Author author);/*** * @Title: updateAuthor* @Description: TODO(修改用户)* @param authro* @return int*/public int updateAuthor(Author authro);/*** * @Title: deleteAturho* @Description: TODO(根据ID删除作者)* @param id* @return int*/public int deleteAuthor(int authorId);}

 

 

2.5、创建接口对应的mapper.xm以author为例

 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.pb.mybatis.mapper.AuthorMapper">
<!--使用resultMap映射  type使用别名,-->
<resultMap type="Author" id="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"/>
</resultMap><!--根据查找一个用户  -->
<select id="findAuthorById" parameterType="int" resultMap="authorResultMap">
SELECT * FROM author
WHERE author_id=#{authorId}
</select><!-- 根据用户名,模糊查询 --><select id="findAuthorByName" parameterType="String" resultMap="authorResultMap">
SELECT * FROM author
WHERE author_username LIKE "%"#{name}"%"
</select><!--添加用户  useGeneratedKeys="true" 使用数据库自增序列keyProperty="authorId"将主键返回
#号中写PO类中的属性
-->
<insert id="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>
<!--修改用户  -->
<update id="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-->
<delete id="deleteAuthor" parameterType="int">
delete from author
where author_id=#{authorId}
</delete>
</mapper>

 

 

 

 

 

三、简单实现增删改查

3.1、测试类以author为例

 

/**
*/
package com.pb.mybatis.mapper;
import java.io.InputStream;
import java.util.Date;
import java.util.List;import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;import com.pb.mybatis.po.Author;/**  * @Title: AuthorMapperTest.java* @Package com.pb.mybatis.mapper* @ClassName AuthorMapperTest* @Description: TODO(测试)* @author 刘楠 * @date 2015-10-29 上午11:57:21* @version V1.0  */
public class AuthorMapperTest {private SqlSessionFactory sqlSessionFactory;/*** * @Title: setUp* @Description: TODO(在每个方法前执行的方法)* @throws Exception void*/@Beforepublic void setUp() throws Exception {String resource="configuration.xml";InputStream in=Resources.getResourceAsStream(resource);//获取会话工厂sqlSessionFactory=new SqlSessionFactoryBuilder().build(in);}/*** * @Title: testFindAuthorById* @Description: TODO(根据查找一个用户)void*/@Testpublic void testFindAuthorById() {//获取会话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*/@Testpublic void testFindAuthorByName() {//获取会话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*/@Testpublic void testAddAuthor() {//获取会话SqlSession sqlSession=sqlSessionFactory.openSession();//Mapper接口AuthorMapper authorMapper=sqlSession.getMapper(AuthorMapper.class);//调用方法Author author=new Author();author.setAuthorUserName("不知道");author.setAuthorPassword("1234567890");author.setAuthorEmail("123456@qq.com");author.setAuthorBio("知道是个什么");author.setRegisterTime(new Date());int num=authorMapper.addAuthor(author);System.out.println("num="+num);System.out.println("authorId="+author.getAuthorId());sqlSession.commit();//关闭会话
        sqlSession.close();}/*** * @Title: testUpdateAuthor* @Description: TODO(修改用户)void*/@Testpublic void testUpdateAuthor() {//获取会话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(new Date());int num=authorMapper.updateAuthor(author);System.out.println("num="+num);System.out.println("authorId="+author.getAuthorId());sqlSession.commit();//关闭会话
                sqlSession.close();}/*** * @Title: testDeleteAuthor* @Description: TODO(根据ID删除作者)void*/@Testpublic void testDeleteAuthor() {//获取会话SqlSession sqlSession=sqlSessionFactory.openSession();//Mapper接口AuthorMapper authorMapper=sqlSession.getMapper(AuthorMapper.class);//调用方法int num=authorMapper.deleteAuthor(10);System.out.println("num="+num);sqlSession.commit();//关闭会话
        sqlSession.close();}}

 

 

四、实现一对一

4.1、建立Blog类

 

package com.pb.mybatis.po;/**  * @Title: Blog.java* @Package com.pb.mybatis.po* @ClassName Blog* @Description: TODO(博客)* @author 刘楠 * @date 2015-10-29 上午9:32:56* @version V1.0  */
public class Blog {//博客IDprivate int blogId;//标题private String blogTitle;//博客作者private Author author;/*** @return the blogId*/public int getBlogId() {return blogId;}/*** @param blogId the blogId to set*/public void setBlogId(int blogId) {this.blogId = blogId;}/*** @return the blogTitle*/public String getBlogTitle() {return blogTitle;}/*** @param blogTitle the blogTitle to set*/public void setBlogTitle(String blogTitle) {this.blogTitle = blogTitle;}/*** @return the author*/public Author getAuthor() {return author;}/*** @param author the author to set*/public void setAuthor(Author author) {this.author = author;}/** (non Javadoc)* <p>Title: toString</p>* <p>Description: 重写toString方法</p>* @return* @see java.lang.Object#toString()*/@Overridepublic String toString() {return "Blog [blogId=" + blogId + ", blogTitle=" + blogTitle+ ", author=" + author + "]";}}

 

4.2、建立BlogMapper接口

 

/**
*/
package com.pb.mybatis.mapper;import java.util.List;import com.pb.mybatis.po.Author;
import com.pb.mybatis.po.Blog;/**  * @Title: BlogMapper.java* @Package com.pb.mybatis.mapper* @ClassName BlogMapper* @Description: TODO(用一句话描述该文件做什么)* @author 刘楠 * @date 2015-10-29 上午11:13:21* @version V1.0  */
public interface BlogMapper {/*** * @Title: findBlogById* @Description: TODO(根据ID查找BLOG)* @param id* @return Blog*/public Blog findBlogById(int id);/*** * @Title: findByName* @Description: TODO(根据博客名查找)* @param name* @return List<Blog>*/public List<Blog> findBlogByName(String blogTitle);/*** * @Title: addBlog* @Description: TODO(添加博客)* @param blog* @return int*/public int addBlog(Blog blog);/*** * @Title: updateBlog* @Description: TODO(修改博客)* @param blog* @return int*/public int updateBlog(Blog blog);/*** * @Title: deleteBlog* @Description: TODO(删除博客)* @param id* @return int*/public int deleteBlog(int id);
}

 

4.3、建立mapper.xml

 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.pb.mybatis.mapper.BlogMapper">
<!--使用ResultMap  -->
<resultMap type="Blog" id="blogResultMap">
<!--主键  -->
<id property="blogId" column="blog_id"/>
<!--标题  -->
<result property="blogTitle" column="blog_title"/>
<!--一对一关联   第一种-->
<association property="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关联-->
<resultMap type="Author" id="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"/>
</resultMap>
<!--  根据ID查询-->
<select id="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>
<!-- 根据名字查询 -->
<select id="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 -->
<insert id="addBlog" parameterType="Blog" useGeneratedKeys="true" keyProperty="blogId">
INSERT INTO blog(blog_title,author_id)
VALUES(#{blogTitle},#{author.authorId})
</insert>
<!--修改  -->
<update id="updateBlog" parameterType="Blog">
UPDATE blog 
SET blog_title=#{blogTitle},
author_id=#{author.authorId}
WHERE blog_id=#{blogId}
</update>
<!--删除  -->
<delete id="deleteBlog" parameterType="int">
delete from blog where blog_id=#{blogId}
</delete></mapper>

 

4.1、测试类

 

package com.pb.mybatis.mapper;import static org.junit.Assert.*;import java.io.InputStream;
import java.util.List;import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;import com.pb.mybatis.po.Author;
import com.pb.mybatis.po.Blog;/**  * @Title: BlogMapperTest.java* @Package com.pb.mybatis.mapper* @ClassName BlogMapperTest* @Description: TODO(用一句话描述该文件做什么)* @author 刘楠 * @date 2015-10-29 下午3:12:52* @version V1.0  */
public class BlogMapperTest {private SqlSessionFactory sqlSessionFactory;@Beforepublic void setUp() throws Exception {String resource="configuration.xml";InputStream in=Resources.getResourceAsStream(resource);//获取会话工厂sqlSessionFactory=new SqlSessionFactoryBuilder().build(in);}/*** Test method for {@link com.pb.mybatis.mapper.BlogMapper#findBlogById(int)}.*/@Testpublic void testFindBlogById() {//获取会话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 {@link com.pb.mybatis.mapper.BlogMapper#findBlogByName(java.lang.String)}.*/@Testpublic void testFindBlogByName() {//获取会话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 {@link com.pb.mybatis.mapper.BlogMapper#addBlog(com.pb.mybatis.po.Blog)}.*/@Testpublic void testAddBlog() {//获取会话SqlSession sqlSession=sqlSessionFactory.openSession();//Mapper接口BlogMapper blogMapper=sqlSession.getMapper(BlogMapper.class);Blog blog=new Blog();blog.setBlogTitle("倚天屠龙记");AuthorMapper authorMapper=sqlSession.getMapper(AuthorMapper.class);//调用方法Author author=authorMapper.findAuthorById(2);blog.setAuthor(author);int num=blogMapper.addBlog(blog);System.out.println("num="+num);System.out.println(blog.getBlogId());sqlSession.commit();sqlSession.close();}/*** Test method for {@link com.pb.mybatis.mapper.BlogMapper#updateBlog(com.pb.mybatis.po.Blog)}.*/@Testpublic void testUpdateBlog() {//获取会话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);int authorNum=authorMapper.updateAuthor(author);int num=blogMapper.updateBlog(blog);System.out.println("authorNum="+authorNum);System.out.println("num="+num);sqlSession.commit();//关闭会话
        sqlSession.close();}/*** Test method for {@link com.pb.mybatis.mapper.BlogMapper#deleteBlog(int)}.*/@Testpublic void testDeleteBlog() {//获取会话SqlSession sqlSession=sqlSessionFactory.openSession();//Mapper接口BlogMapper blogMapper=sqlSession.getMapper(BlogMapper.class);int num=blogMapper.deleteBlog(11);System.out.println("num="+num);sqlSession.commit();sqlSession.close();}}

 

 

 

五、一对多

5.1、建立Posts类

 

package com.pb.mybatis.po;import java.util.Date;/**  * @Title: Posts.java* @Package com.pb.mybatis.po* @ClassName Posts* @Description: TODO(Blog文章)* @author 刘楠 * @date 2015-10-29 上午9:31:22* @version V1.0  */
public class Posts {//文章IDprivate int postId;//文件主题private String postSubject;//主体内容private String postBody;//文章建立时间private Date createTime;/*** @return the postId*/public int getPostId() {return postId;}/*** @param postId the postId to set*/public void setPostId(int postId) {this.postId = postId;}/*** @return the postSubject*/public String getPostSubject() {return postSubject;}/*** @param postSubject the postSubject to set*/public void setPostSubject(String postSubject) {this.postSubject = postSubject;}/*** @return the postBody*/public String getPostBody() {return postBody;}/*** @param postBody the postBody to set*/public void setPostBody(String postBody) {this.postBody = postBody;}/*** @return the createTime*/public Date getCreateTime() {return createTime;}/*** @param createTime the createTime to set*/public void setCreateTime(Date createTime) {this.createTime = createTime;}/** (non Javadoc)* <p>Title: toString</p>* <p>Description:重写toString方法</p>* @return* @see java.lang.Object#toString()*/@Overridepublic String toString() {return "Posts [postId=" + postId + ", postSubject=" + postSubject+ ", postBody=" + postBody +", createTime="+ createTime + "]";}}

 

5.2、在blog类中添加List

 

package com.pb.mybatis.po;import java.util.List;/**  * @Title: Blog.java* @Package com.pb.mybatis.po* @ClassName Blog* @Description: TODO(博客)* @author 刘楠 * @date 2015-10-29 上午9:32:56* @version V1.0  */
public class Blog {//博客IDprivate int blogId;//标题private String blogTitle;//博客作者private Author author;//文章Listprivate List<Posts> posts;/*** @return the blogId*/public int getBlogId() {return blogId;}/*** @param blogId the blogId to set*/public void setBlogId(int blogId) {this.blogId = blogId;}/*** @return the blogTitle*/public String getBlogTitle() {return blogTitle;}/*** @param blogTitle the blogTitle to set*/public void setBlogTitle(String blogTitle) {this.blogTitle = blogTitle;}/*** @return the author*/public Author getAuthor() {return author;}/*** @param author the author to set*/public void setAuthor(Author author) {this.author = author;}/*** @return the posts*/public List<Posts> getPosts() {return posts;}/*** @param posts the posts to set*/public void setPosts(List<Posts> posts) {this.posts = posts;}/** (non Javadoc)* <p>Title: toString</p>* <p>Description: </p>* @return* @see java.lang.Object#toString()*/@Overridepublic String toString() {return "Blog [blogId=" + blogId + ", blogTitle=" + blogTitle+ ", author=" + author + ", posts=" + posts + "]";}}

 

5.3、修改blogMapper.xml

 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.pb.mybatis.mapper.BlogMapper">
<!--使用ResultMap  -->
<resultMap type="Blog" id="blogResultMap">
<!--主键  -->
<id property="blogId" column="blog_id"/>
<!--标题  -->
<result property="blogTitle" column="blog_title"/>
<!--一对一关联   第一种-->
<association property="author" resultMap="authorResultMap"/>
<!--一对多关联  -->
<collection property="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  -->
<resultMap type="Posts" id="postsResultMap">
<id property="postId" column="post_id"/>
<result property="postSubject" column="post_subject"/>
<result property="postBody" column="post_body"/>
<result property="createTime" column="createtime"/>
</resultMap>
<!--使用resultMap映射  type使用别名,单独使用Author关联-->
<resultMap type="Author" id="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"/>
</resultMap>
<!--  根据ID查询-->
<select id="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>
<!-- 根据名字查询 -->
<select id="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 -->
<insert id="addBlog" parameterType="Blog" useGeneratedKeys="true" keyProperty="blogId">
INSERT INTO blog(blog_title,author_id)
VALUES(#{blogTitle},#{author.authorId})
</insert>
<!--修改  -->
<update id="updateBlog" parameterType="Blog">
UPDATE blog 
SET blog_title=#{blogTitle},
author_id=#{author.authorId}
WHERE blog_id=#{blogId}
</update>
<!--删除  -->
<delete id="deleteBlog" parameterType="int">
delete from blog where blog_id=#{blogId}
</delete></mapper>

 

 

5.4、测试

测试类不变

转载于:https://www.cnblogs.com/liunanjava/p/4919752.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/397367.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

零基础学Java的10个方法

2019独角兽企业重金招聘Python工程师标准>>> 版权声明&#xff1a;本文为北京尚学堂原创文章&#xff0c;未经允许不得转载。​ 零基础学Java只要方法得当&#xff0c;依然有机会学习好Java编程。 但作为初学者可以通过制定一些合理清晰的学习计划。 在帮你屡清楚思…

scp windows 和 linux 远程复制 (双向)

一下命令在cmd中 从w -> l : scp D:\a.txt root192.168.2.113:/home/a 从l -> w: scp root192.168.2.113:/home/aaa d:/b.txt 按说在Linux中也可以&#xff0c;但是不知道怎么的只有在winodws上行&#xff0c;在linux上就会报 ssh: connect to host 192.168.2.157 port 2…

北京尚学堂|程序员的智慧

2019独角兽企业重金招聘Python工程师标准>>> 版权声明&#xff1a;本文为北京尚学堂原创文章&#xff0c;未经允许不得转载。 编程是一种创造性的工作&#xff0c;是一门艺术。精通任何一门艺术&#xff0c;都需要很多的练习和领悟&#xff0c;所以这里提出的“智慧…

翼城中学2021高考成绩查询入口,2021年临汾中考分数线查询(4)

临汾2021年中考分数线查询 2021临汾中考录取分数线 19年临汾中考各校录取分数线 临汾各高中录取分数线 临汾2021中考录取线查询 中考信息网提供2021临汾中考分数线查询信息。临汾中考录取分数线预计7月初公布&#xff0c;届时考生可登陆临汾招生考试网官网查看分数线情况。2…

配置Tomcat使用HTTP/2

转自&#xff1a; https://zhuanlan.zhihu.com/p/21349186 前情提要&#xff1a; Tomcat高效响应的秘密(一) Sendfile与Gzip Tomcat高效响应的秘密(二) keep alive 前面高效响应的两篇&#xff0c;我们分析了Sendfile的特性以及HTTP1.1的keep-alive特性&#xff0c;基于这些功…

通过NSNotification来监听键盘弹出和弹回

在通知中心建立一个广播来监听键盘的弹出和弹回&#xff0c;在监听事件中加入触发事件的一些操作。 [[NSNotificationCenter defaultCenter]addObserver:self selector:selector(keyboardWillChange:) name:UIKeyboardWillChangeFrameNotification object:nil];[[NSNotificatio…

IT综合学习网站收集

最近整理了一下曾经使用过的IT从入门到广泛的综合类基础学习网站&#xff0c;记录下来&#xff0c;以便初学者使用&#xff1a; 1.http://www.w3school.com.cn/ 中文版基础在线学习平台 2.http://www.runoob.com/ 中文版基础在线学习平台&#xff08;和W3类似&#xff09; 3.h…

mac安装gdb及为gdb进行代码签名

1. 安装gdb GDB作为一个强大的c/c调试工具&#xff0c;一直是程序猿们的良好伴侣&#xff0c;但转到Mac os才发现竟然没有默认安装&#xff0c;所幸还有强大的homebrew工具&#xff1a; brew install homebrew/dupes/gdb然后就是漫长的等待编译安装时间了&#xff0c;安装完成后…

Python学习---Django的基础操作180116

Django创建数据库操作 django流程之model实例 settigs.py&#xff1a;更改Django2.0.1的配置&#xff0c;更新为之前的路径配置 DIRS: [os.path.join(BASE_DIR, templates)], # 设置templates的路径为Django以前版本 # DIRS: [], # 注释掉该行&#xff0c;此为Django 2.0…

订阅Jenkins的邮件列表,获取最新的信息

进入https://jenkins.io/content/mailing-lists/ 点击感兴趣的话题 选择【archive】跳转到谷歌讨论组 最后&#xff0c;点击左上角的【Subscribe】即可加入Google Groups 备注&#xff1a;其实谷歌讨论组是一个很好用的东西&#xff0c;每个人都可以上去建&#xff0c;对于集成…

英语四六级和计算机二级是一,大学里最难考证书排名,四六级和计算机根本排不进前三...

大学是我们提高自身技能最好的一个时期&#xff0c;除了平时的课程和一些社团活动之外&#xff0c;还有一件最最必不可少的事情&#xff0c;那就是考证&#xff0c;而这也是为我们以后工作打好基础&#xff0c;为自己多准备一些敲门砖。我国各个行业都有属于自己的证书&#xf…

Fedora 安装后需要做的第一件事

一直以来&#xff0c;Red Hat 系的许多教程&#xff0c;都会建议你关闭 SELinux。确实&#xff0c;启用 SELinux 可能会造成许多莫名其妙的错误。但在实际生产环境&#xff0c;甚至是用户工作站&#xff0c;Red Hat 都建议将 SELinux 设为 enforcing 模式&#xff0c;因为它在关…

html文件怎么导出stl文件,各种3D建模软件导出STL文件的小技巧(一)

很多用户在提交3D模型文件的时候&#xff0c;常常有这样的困惑&#xff1a;什么是STL 格式文件&#xff0c;怎么获取STL 格式文件呢&#xff1f;STL 格式文件是在计算机图形应用系统中&#xff0c;用于表示三角形网格的一种文件格式。它也是3D打印机在执行3D打印程序时&#xf…

angularjs 中的scope继承关系——(2)

转自&#xff1a;http://www.lovelucy.info/understanding-scopes-in-angularjs.html angularjs 中的scope继承关系 ng-include 假设在我们的 controller 中&#xff0c; $scope.myPrimitive 50; $scope.myObject {aNumber: 11}; HTML 为&#xff1a; <script type&quo…

Android界面菜单(4)—快捷菜单

2019独角兽企业重金招聘Python工程师标准>>> 快捷菜单 当用户点击界面上某个元素超过2秒后&#xff0c;将启动注册到该界面的快捷菜单。 步骤&#xff1a; 1.代码动态生成菜单 final static int CONTEXT_MENU_1 Menu.FIRST;final static int CONTEXT_MENU_2 Menu…

Echarts地图编写

1.引入echarts库文件 <script charset"utf-8" type"text/javascript" language"javascript" src"echarts-2.2.7/doc/example/www/js/echarts.js"></script> 2.在页面中新建div用于地图展示 <div id"main" st…

威海职业学院计算机专业宿舍,2021年威海职业学院新生宿舍条件和宿舍环境图片...

每年高考结束后&#xff0c;威海职业学院新生被录取同学们陆续都到校报到~而宿舍作为同学们朝夕相处之场所&#xff0c;如果不懂相处之道&#xff0c;难免会摩擦不断&#xff0c;更有甚者堪比宫斗大戏。所以各位大学新生一定要珍惜室友之间的友情&#xff0c;彼此处好关系。本文…

计算机专业录取分数及大学排名,计算机专业录取分数最高的大学有哪些?附排名前50大学名单...

高考结束之后&#xff0c;不少即将迎接高考的家长对于很多专业的录取情况都抱有很大的兴趣&#xff0c;都比较关心自己的理想专业大概能上哪些大学。今天&#xff0c;小编将为大家以山东高考计算机专业各大学录取分数进行排名&#xff0c;供下一届高考生参考。计算机专业作为近…

letsencrypt 自动续期不关闭nginx

为什么80%的码农都做不了架构师&#xff1f;>>> 已失效 corntab -e 5 0 1 * * /opt/letsencrypt/letsencrypt-auto --config /etc/letsencrypt/webroot.ini -d <domain> certonly && sudo service nginx reload/etc/letsencrypt/webroot.ini rsa-key…

loss低但精确度低_低光照图像增强网络-RetinexNet(model.py解析【2】)

论文地址&#xff1a;https://arxiv.org/pdf/1808.04560.pdf代码地址&#xff1a;https://github.com/weichen582/RetinexNet解析目录&#xff1a;https://zhuanlan.zhihu.com/p/88761829整个模型架构被实现为一个类&#xff1a;class lowlight_enhance(object):其构造函数实现…