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.pswp.cn/news/397367.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/397367.shtml
英文地址,請注明出處:http://en.pswp.cn/news/397367.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

零基礎學Java的10個方法

2019獨角獸企業重金招聘Python工程師標準>>> 版權聲明&#xff1a;本文為北京尚學堂原創文章&#xff0c;未經允許不得轉載。? 零基礎學Java只要方法得當&#xff0c;依然有機會學習好Java編程。 但作為初學者可以通過制定一些合理清晰的學習計劃。 在幫你屢清楚思…

html 轉換為cshtml,使用Html而不是csHtml

我想使用純HTML頁面而不是使用MVC .net的cshtml . 但是當我通過右鍵單擊索引添加視圖時&#xff0c;我只能看到兩個選項 .public class HomeController : Controller{//// GET: /Home/public ActionResult Index(){return View();}}Cshtml(剃刀)Aspx論壇但仍無濟于事 . 我仍然沒…

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…

JSP EL表達式 param、paramValues的使用

JSP EL表達式 param、paramValues的使用&#xff1a; <% page language"java" import"java.util.*" pageEncoding"UTF-8"%> <%String path request.getContextPath();String basePath request.getScheme() "://" request…

配置Tomcat使用HTTP/2

轉自&#xff1a; https://zhuanlan.zhihu.com/p/21349186 前情提要&#xff1a; Tomcat高效響應的秘密(一) Sendfile與Gzip Tomcat高效響應的秘密(二) keep alive 前面高效響應的兩篇&#xff0c;我們分析了Sendfile的特性以及HTTP1.1的keep-alive特性&#xff0c;基于這些功…

asp.net razor html,從控制臺應用程序中的ASP.NET Razor模板生成HTML的當前最佳解決方案是什么?...

ServiceStack是用于呈現Razor視圖頁面的另一個選項。 盡管它已針對集成到ASP.NET或HttpListener Web Host中進行了優化(并提供了用于在目錄中自動發現和注冊視圖頁面&#xff0c;即時重新編譯修改后的頁面等的API)&#xff0c;但它還支持靜態生成視圖頁面 &#xff1a;var razo…

通過NSNotification來監聽鍵盤彈出和彈回

在通知中心建立一個廣播來監聽鍵盤的彈出和彈回&#xff0c;在監聽事件中加入觸發事件的一些操作。 [[NSNotificationCenter defaultCenter]addObserver:self selector:selector(keyboardWillChange:) name:UIKeyboardWillChangeFrameNotification object:nil];[[NSNotificatio…

Xcode緩存數據清除

1. 移除 APP 打包的ipa歷史版本(Archives) 不可恢復&#xff0c;就是你打的包&#xff0c;如果需要dysm文件&#xff0c;及時備份 路徑&#xff1a;~/Library/Developer/Xcode/Archives 2. 移除對舊設備的支持 可重新生成&#xff1b;再連接舊設備調試時&#xff0c;會重新自動…

IT綜合學習網站收集

最近整理了一下曾經使用過的IT從入門到廣泛的綜合類基礎學習網站&#xff0c;記錄下來&#xff0c;以便初學者使用&#xff1a; 1.http://www.w3school.com.cn/ 中文版基礎在線學習平臺 2.http://www.runoob.com/ 中文版基礎在線學習平臺&#xff08;和W3類似&#xff09; 3.h…

電大計算機網絡網考,電大計算機網絡(本)學習周期01任務A_0009答案

一、單項選擇題(共 20 道試題&#xff0c;共 60 分。)1. ( )和數據通信是計算機網絡最基本的兩大功能。A. 資源共享B. 病毒管理C. 用戶管理D. 站點管理2. 計算機網絡系統是由通信子網和( )子網組成的。A. 資源B. 數字C. 信息D. 模擬3. 網絡資源子網負責( )。A. 數據通信B. 數字…

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…

PO、VO、DAO、BO、POJO

一、PO :(persistant object )&#xff0c;持久對象 可以看成是與數據庫中的表相映射的java對象。使用Hibernate來生成PO是不錯的選擇。二、VO :(value object) &#xff0c;值對象通常用于業務層之間的數據傳遞&#xff0c;和PO一樣也是僅僅包含數據而已。但應是抽象出的業務對…

計算機網絡是將地理知識,計算機網絡的基礎知識精選.ppt

計算機網絡的基礎知識精選習題演練 1&#xff0c;WAN的中文含義是()。   A. 局域網   B. 城域網 C. 廣域網   D. 增值網 2&#xff0c;LAN的中文含義是()。   A. 局域網 B. 城域網 C. 廣域網 D. 增值網 3&#xff0c;MAN的中文含義是()。   A. 局域網   B. 城域網 C…

VBA——Msgbox

MsgBox(prompt[,buttons][,title][,helpfile,context]) 參數說明 prompt - 必需的參數。在對話框中顯示為消息的字符串。提示的最大長度大約為1024個字符。 如果消息擴展為多行&#xff0c;則可以使用每行之間的回車符(Chr(13))或換行符(Chr(10))來分隔行。buttons - 可選參數。…

訂閱Jenkins的郵件列表,獲取最新的信息

進入https://jenkins.io/content/mailing-lists/ 點擊感興趣的話題 選擇【archive】跳轉到谷歌討論組 最后&#xff0c;點擊左上角的【Subscribe】即可加入Google Groups 備注&#xff1a;其實谷歌討論組是一個很好用的東西&#xff0c;每個人都可以上去建&#xff0c;對于集成…

內存的管理方式

1、內存的區域 對于內存的區域劃分上&#xff0c;不同的區域劃分上都各有不同。 劃分1&#xff1a; 代碼區、堆、棧、 全局區&#xff08;靜態存儲區&#xff09;、 文字常量區、 劃分2&#xff1a; 代碼段、堆、棧、 data段、BSS段、文字常量區 全局區&#xff1a; 又成為靜…

英語四六級和計算機二級是一,大學里最難考證書排名,四六級和計算機根本排不進前三...

大學是我們提高自身技能最好的一個時期&#xff0c;除了平時的課程和一些社團活動之外&#xff0c;還有一件最最必不可少的事情&#xff0c;那就是考證&#xff0c;而這也是為我們以后工作打好基礎&#xff0c;為自己多準備一些敲門磚。我國各個行業都有屬于自己的證書&#xf…