您好,欢迎访问一九零五行业门户网

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 {    //作者id
   private 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()     */
   @override    public 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 configuration
public "-//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 mapper
public "-//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     */
   @before    public void setup() throws exception {
       string resource=configuration.xml;
       inputstream in=resources.getresourceasstream(resource);        //获取会话工厂
       sqlsessionfactory=new sqlsessionfactorybuilder().build(in);
   }    /**
    *
    * @title: testfindauthorbyid
* @description: todo(根据查找一个用户)
    void     */
   @test    public 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     */
   @test    public 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     */
   @test    public 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     */
   @test    public 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     */
   @test    public 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 {    //博客id
   private 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()     */
   @override    public 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 mapper
public "-//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;
@before    public 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)}.     */
   @test    public 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)}.     */
   @test    public 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)}.     */
   @test    public 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)}.     */
   @test    public 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)}.     */
   @test    public 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 {    //文章id
   private 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()     */
   @override    public 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 {    //博客id
   private int blogid;    
   //标题
   private string blogtitle;    
   //博客作者
   private author author;    
   //文章list
   private 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()     */
   @override    public string 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"><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、测试
测试类不变
以上就是mybatis入门(二)---一对一,一对多的内容。
其它类似信息

推荐信息