Mybatis介紹(一)

這裏介紹的mybatis比較簡單, 我作爲一個初學者, 記錄下我的在學習中方法, 若是那裏出錯, 但願讀者朋友們見諒.html

首先這裏介紹一下咱們下面用的表結構:前端

author表是保存了做者的我的信息, 由於咱們在這裏作測試, 因此就簡單的定義幾個字段.java

blog表是保存誰寫了博客的內容, 這裏也是幾個簡單的字段.web

comment表是保存對哪篇博客評論, 也是幾個簡單的字段.spring

注意: 這三張表的id都是自增型, 你也能夠作其餘的改變, 這裏是爲了方便.sql

下面給出了幾張表格建立的sql語句:數據庫

CREATE TABLE `author` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(25) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `age` int(5) NULL DEFAULT NULL, `email` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `country` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,  PRIMARY KEY (`id`) ); CREATE TABLE `blog` ( `id` int(11) NOT NULL AUTO_INCREMENT, `authorid` int(11) NULL DEFAULT NULL, `title` varchar(35) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `mainbody` text CHARACTER SET utf8 COLLATE utf8_general_ci NULL, `creattime` varchar(70) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,  PRIMARY KEY (`id`) ); CREATE TABLE `comment` ( `id` int(11) NOT NULL AUTO_INCREMENT, `blogid` int(11) NULL DEFAULT NULL, `content` text CHARACTER SET utf8 COLLATE utf8_general_ci NULL, `creattime` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,  PRIMARY KEY (`id`) );

 使用maven+springmvc+mabatis+spring搭建web環境, 能夠參考博客: http://www.javashuo.com/article/p-grymgytt-do.html, 這裏就不詳細的介紹了.mybatis

 這裏主要介紹mybatis的用法, 首先使用Mybatis Generator生成pojo/dao/mapping三個文件, 即實體類、DAO接口和Mapping映射文件.mvc

 能夠參考博客:  https://blog.csdn.net/zhshulin/article/details/23912615, 下面就開始簡單介紹Mybatis的使用.app

 1.  看一下三個表pojo(Plain Ordinary Java Object), 即實體類

package com.springdemo.pojo; public class Author { private Integer id; private String name; private Integer age; private String email; private String country; /* getting and setting function */ } package com.springdemo.pojo; public class Blog { private Integer id; private Integer authorid; private String title; private String creattime; private String mainbody; /* getting and setting function */ } package com.springdemo.pojo; public class Comment { private Integer id; private Integer blogid; private String creattime; private String content; /* getting and setting function */ }
View Code

2.  再看一下三個表的dao(Data Access Object), 即dao接口

package com.springdemo.dao public interface AuthorMapper { int deleteByPrimaryKey(Integer id); int insert(Author record); int insertSelective(Author record); Author selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(Author record); int updateByPrimaryKey(Author record); } package com.springdemo.dao public interface BlogMapper { int deleteByPrimaryKey(Integer id); int insert(Blog record); int insertSelective(Blog record); Blog selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(Blog record); int updateByPrimaryKeyWithBLOBs(Blog record); int updateByPrimaryKey(Blog record); } package com.springdemo.dao public interface CommentMapper { int deleteByPrimaryKey(Integer id); int insert(Comment record); int insertSelective(Comment record); Comment selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(Comment record); int updateByPrimaryKeyWithBLOBs(Comment record); int updateByPrimaryKey(Comment record); }
View Code

3.  再看一下三個表的mapping, 即Mapping映射

<?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.springdemo.dao.AuthorMapper" >
  <resultMap id="BaseResultMap" type="com.springdemo.pojo.Author" >
    <id column="id" property="id" jdbcType="INTEGER" />
    <result column="name" property="name" jdbcType="VARCHAR" />
    <result column="age" property="age" jdbcType="INTEGER" />
    <result column="email" property="email" jdbcType="VARCHAR" />
    <result column="country" property="country" jdbcType="VARCHAR" />
  </resultMap>
  <sql id="Base_Column_List" > id, name, age, email, country </sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" > select <include refid="Base_Column_List" /> from author where id = #{id,jdbcType=INTEGER} </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" > delete from author where id = #{id,jdbcType=INTEGER} </delete>
  <insert id="insert" parameterType="com.springdemo.pojo.Author" > insert into author (id, name, age, email, country) values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}, #{email,jdbcType=VARCHAR}, #{country,jdbcType=VARCHAR}) </insert>
  <insert id="insertSelective" parameterType="com.springdemo.pojo.Author" > insert into author <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="id != null" > id, </if>
      <if test="name != null" > name, </if>
      <if test="age != null" > age, </if>
      <if test="email != null" > email, </if>
      <if test="country != null" > country, </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="id != null" > #{id,jdbcType=INTEGER}, </if>
      <if test="name != null" > #{name,jdbcType=VARCHAR}, </if>
      <if test="age != null" > #{age,jdbcType=INTEGER}, </if>
      <if test="email != null" > #{email,jdbcType=VARCHAR}, </if>
      <if test="country != null" > #{country,jdbcType=VARCHAR}, </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.springdemo.pojo.Author" > update author <set >
      <if test="name != null" > name = #{name,jdbcType=VARCHAR}, </if>
      <if test="age != null" > age = #{age,jdbcType=INTEGER}, </if>
      <if test="email != null" > email = #{email,jdbcType=VARCHAR}, </if>
      <if test="country != null" > country = #{country,jdbcType=VARCHAR}, </if>
    </set> where id = #{id,jdbcType=INTEGER} </update>
  <update id="updateByPrimaryKey" parameterType="com.springdemo.pojo.Author" > update author set name = #{name,jdbcType=VARCHAR}, age = #{age,jdbcType=INTEGER}, email = #{email,jdbcType=VARCHAR}, country = #{country,jdbcType=VARCHAR} where id = #{id,jdbcType=INTEGER} </update>
</mapper>

<?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.springdemo.dao.BlogMapper" >
  <resultMap id="BaseResultMap" type="com.springdemo.pojo.Blog" >
    <id column="id" property="id" jdbcType="INTEGER" />
    <result column="authorid" property="authorid" jdbcType="INTEGER" />
    <result column="title" property="title" jdbcType="VARCHAR" />
    <result column="creattime" property="creattime" jdbcType="VARCHAR" />
  </resultMap>
  <resultMap id="ResultMapWithBLOBs" type="com.springdemo.pojo.Blog" extends="BaseResultMap" >
    <result column="mainbody" property="mainbody" jdbcType="LONGVARCHAR" />
  </resultMap>
  <sql id="Base_Column_List" > id, authorid, title, creattime </sql>
  <sql id="Blob_Column_List" > mainbody </sql>
  <select id="selectByPrimaryKey" resultMap="ResultMapWithBLOBs" parameterType="java.lang.Integer" > select <include refid="Base_Column_List" /> , <include refid="Blob_Column_List" /> from blog where id = #{id,jdbcType=INTEGER} </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" > delete from blog where id = #{id,jdbcType=INTEGER} </delete>
  <insert id="insert" parameterType="com.springdemo.pojo.Blog" > insert into blog (id, authorid, title, creattime, mainbody) values (#{id,jdbcType=INTEGER}, #{authorid,jdbcType=INTEGER}, #{title,jdbcType=VARCHAR}, #{creattime,jdbcType=VARCHAR}, #{mainbody,jdbcType=LONGVARCHAR}) </insert>
  <insert id="insertSelective" parameterType="com.springdemo.pojo.Blog" > insert into blog <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="id != null" > id, </if>
      <if test="authorid != null" > authorid, </if>
      <if test="title != null" > title, </if>
      <if test="creattime != null" > creattime, </if>
      <if test="mainbody != null" > mainbody, </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="id != null" > #{id,jdbcType=INTEGER}, </if>
      <if test="authorid != null" > #{authorid,jdbcType=INTEGER}, </if>
      <if test="title != null" > #{title,jdbcType=VARCHAR}, </if>
      <if test="creattime != null" > #{creattime,jdbcType=VARCHAR}, </if>
      <if test="mainbody != null" > #{mainbody,jdbcType=LONGVARCHAR}, </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.springdemo.pojo.Blog" > update blog <set >
      <if test="authorid != null" > authorid = #{authorid,jdbcType=INTEGER}, </if>
      <if test="title != null" > title = #{title,jdbcType=VARCHAR}, </if>
      <if test="creattime != null" > creattime = #{creattime,jdbcType=VARCHAR}, </if>
      <if test="mainbody != null" > mainbody = #{mainbody,jdbcType=LONGVARCHAR}, </if>
    </set> where id = #{id,jdbcType=INTEGER} </update>
  <update id="updateByPrimaryKeyWithBLOBs" parameterType="com.springdemo.pojo.Blog" > update blog set authorid = #{authorid,jdbcType=INTEGER}, title = #{title,jdbcType=VARCHAR}, creattime = #{creattime,jdbcType=VARCHAR}, mainbody = #{mainbody,jdbcType=LONGVARCHAR} where id = #{id,jdbcType=INTEGER} </update>
  <update id="updateByPrimaryKey" parameterType="com.springdemo.pojo.Blog" > update blog set authorid = #{authorid,jdbcType=INTEGER}, title = #{title,jdbcType=VARCHAR}, creattime = #{creattime,jdbcType=VARCHAR} where id = #{id,jdbcType=INTEGER} </update>
</mapper>

<?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.springdemo.dao.CommentMapper" >
  <resultMap id="BaseResultMap" type="com.springdemo.pojo.Comment" >
    <id column="id" property="id" jdbcType="INTEGER" />
    <result column="blogid" property="blogid" jdbcType="INTEGER" />
    <result column="creattime" property="creattime" jdbcType="VARCHAR" />
  </resultMap>
  <resultMap id="ResultMapWithBLOBs" type="com.springdemo.pojo.Comment" extends="BaseResultMap" >
    <result column="content" property="content" jdbcType="LONGVARCHAR" />
  </resultMap>
  <sql id="Base_Column_List" > id, blogid, creattime </sql>
  <sql id="Blob_Column_List" > content </sql>
  <select id="selectByPrimaryKey" resultMap="ResultMapWithBLOBs" parameterType="java.lang.Integer" > select <include refid="Base_Column_List" /> , <include refid="Blob_Column_List" /> from comment where id = #{id,jdbcType=INTEGER} </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" > delete from comment where id = #{id,jdbcType=INTEGER} </delete>
  <insert id="insert" parameterType="com.springdemo.pojo.Comment" > insert into comment (id, blogid, creattime, content) values (#{id,jdbcType=INTEGER}, #{blogid,jdbcType=INTEGER}, #{creattime,jdbcType=VARCHAR}, #{content,jdbcType=LONGVARCHAR}) </insert>
  <insert id="insertSelective" parameterType="com.springdemo.pojo.Comment" > insert into comment <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="id != null" > id, </if>
      <if test="blogid != null" > blogid, </if>
      <if test="creattime != null" > creattime, </if>
      <if test="content != null" > content, </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="id != null" > #{id,jdbcType=INTEGER}, </if>
      <if test="blogid != null" > #{blogid,jdbcType=INTEGER}, </if>
      <if test="creattime != null" > #{creattime,jdbcType=VARCHAR}, </if>
      <if test="content != null" > #{content,jdbcType=LONGVARCHAR}, </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.springdemo.pojo.Comment" > update comment <set >
      <if test="blogid != null" > blogid = #{blogid,jdbcType=INTEGER}, </if>
      <if test="creattime != null" > creattime = #{creattime,jdbcType=VARCHAR}, </if>
      <if test="content != null" > content = #{content,jdbcType=LONGVARCHAR}, </if>
    </set> where id = #{id,jdbcType=INTEGER} </update>
  <update id="updateByPrimaryKeyWithBLOBs" parameterType="com.springdemo.pojo.Comment" > update comment set blogid = #{blogid,jdbcType=INTEGER}, creattime = #{creattime,jdbcType=VARCHAR}, content = #{content,jdbcType=LONGVARCHAR} where id = #{id,jdbcType=INTEGER} </update>
  <update id="updateByPrimaryKey" parameterType="com.springdemo.pojo.Comment" > update comment set blogid = #{blogid,jdbcType=INTEGER}, creattime = #{creattime,jdbcType=VARCHAR} where id = #{id,jdbcType=INTEGER} </update>
</mapper>
View Code

mybatis的使用, 關鍵在於要要寫好mapping映射, 使用工具生成的是最簡單的curd的方法, 如今咱們來增長一個咱們自定義的方法.

首先在mapping的文件中寫一個映射, 咱們就在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.springdemo.dao.BlogMapper" >
  ......
  <insert id="insertBlogByList" useGeneratedKeys="true" keyProperty="id" parameterType="java.util.List"> insert into blog (authorid, title, creattime, mainbody) values <foreach item="item" collection="list" separator=","> (#{item.authorid,jdbcType=INTEGER}, #{item.title,jdbcType=VARCHAR}, #{item.creattime,jdbcType=VARCHAR}, #{item.mainbody,jdbcType=LONGVARCHAR}) </foreach>
  </insert>
  ...... 
</mapper>

這段xml的代碼主要就是批量插入數據, 並且id是自增加的,  數據以list的形式傳入進來, 而後循環插入到blog表中.

而後咱們要在BlogMapper.java的dao中加一個接口, 代碼以下:

package com.springdemo.dao; public interface BlogMapper { ...... int insertBlogByList(List<Blog> listBlog); ...... }
注意這裏的接口名字要和咱們以前在xml中加入的id值相同才行, 由於這樣mybatis纔會映射.
即在BlogMapper.xml中寫的insert語句id是insertBlogByList,
那麼這裏的定義的接口必須也是這個, 並且參數的類型也必須同樣, 這一點切記。

最後咱們要在controller中去調用(由於這裏我是用springmvc寫的,全部用mvc思想去寫調用,你也能夠隨便寫一個方法去調用, 這裏給出個人調用方法):

//下面是BlogController.java的代碼
package com.springdemo.controller; @Controller @RequestMapping(value = "/blog") public class BlogController { private static final Logger LOG = LogManager.getLogger(); @Autowired private BlogService blogService;    //這裏是把前端的值獲取到,而後再存入到數據庫中, 最後返回狀態
    @RequestMapping(value="/insert", method = RequestMethod.POST) public void insertBlog(HttpServletRequest request, HttpServletResponse response) { String status = "{\"status\":\"failure\"}"; int authorid = Integer.parseInt(request.getParameter("authorid")); String title = String.valueOf(request.getParameter("title")); String mainbody = String.valueOf(request.getParameter("mainbody")); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date now = new Date(); String creattime = df.format(now); List<Blog> listBlog = new ArrayList<Blog>(); Blog blog = new Blog(); blog.setAuthorid(authorid); blog.setTitle(title); blog.setMainbody(mainbody); blog.setCreattime(creattime); listBlog.add(blog); int affectRow = blogService.insertBlogByList(listBlog); if (affectRow != 0) { status = "{\"status\":\"success\"}"; } response.setContentType("text/html;UTF-8"); try (PrintWriter writer = response.getWriter();) { writer.write(status); writer.flush(); } catch (IOException e) { LOG.error(e.getMessage(), e); } } } ----------------------------------------------------------
// 下面是BlogService.java的代碼
package com.springdemo.service; import java.util.List; 
// 這裏不須要繼承BlogMapper接口, 經過spring註解直接使用 @Service(value
="blogService") public class BlogService { @Resource private BlogMapper blogMapper; public int insertBlogByList(List<Blog> listBlog) { int affectRow = 0; affectRow = this.blogMapper.insertBlogByList(listBlog); return affectRow; } }

 這樣就簡單的完成了在xml中創建sql語句, 而後經過映射轉換到java中, 最後去執行.

 待續......

相關文章
相關標籤/搜索