Mybatis介绍(一)
这里介绍的mybatis比较简单, 我做为一个初学者, 记录下个人在学习中方法, 如果那里出错, 希望读者朋友们见谅.
首先这里介绍一下我们下面用的表结构:
author表是保存了作者的个人信息, 因为我们在这里做测试, 所以就简单的定义几个字段.
blog表是保存谁写了博客的内容, 这里也是几个简单的字段.
comment表是保存对哪篇博客评论, 也是几个简单的字段.
注意: 这三张表的id都是自增型, 你也可以做其他的改变, 这里是为了方便.
下面给出了几张表格创建的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环境, 可以参考博客: https://www.cnblogs.com/jay36/p/7762448.html, 这里就不详细的介绍了.
这里主要介绍mybatis的用法, 首先使用Mybatis Generator生成pojo/dao/mapping三个文件, 即实体类、DAO接口和Mapping映射文件.
可以参考博客: https://blog.csdn.net/zhshulin/article/details/23912615, 下面就开始简单介绍Mybatis的使用.
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 */
- }
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);
- }
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>
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中, 最后去执行.
待续......
Mybatis介绍(一)的更多相关文章
- MyBatis - 介绍、简单入门程序
JDBC编程中的问题 1. 将SQL语句硬编码到Java代码,不利于系统维护. 设想如何解决:将SQL单独抽取出来,在配置文件(xml方式.properties文件)进行配置. ...
- Mybatis学习笔记(一) —— mybatis介绍
一.Mybatis介绍 MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名 ...
- (转)MyBatis框架的学习(一)——MyBatis介绍
http://blog.csdn.net/yerenyuan_pku/article/details/71699343 MyBatis介绍 MyBatis本是apache的一个开源项目iBatis,2 ...
- MyBatis 介绍
MyBatis 介绍 MyBatis 是一款优秀的 ORM(Object Relational Mapping,对象关系映射)框架,它可以通过对象和数据库之间的映射,将程序中的对象自动存储到数据库中. ...
- mybatis介绍--基于个人学习JavaWeb的使用
mybatis介绍 该博文放在javaWeb系列下,目的是记录我们javaWeb阶段所学的知识 @time=2022/3/11/11:52(最近休息玩了两天,今天重新启动生活) 一.mybatis发展 ...
- mybatis介绍与环境搭建
一.不用纯jdbc的原因,即缺点. 1.数据库理解,使用时创建,不用时释放,会对数据库进行频繁的链接开启和关闭,造成数据库的资源浪费,影响数据库的性能.设想:使用数据库的连接池.2.将sql语句硬编码 ...
- 深入浅出MyBatis:JDBC和MyBatis介绍
JDBC相关概念 Java程序都是通过JDBC连接数据库的,通过SQL对数据库编程,JDBC是由SUN公司提出的一些列规范,只定义了接口规范,具体实现由各个数据库厂商去实现,它是一种典型的桥接模式. ...
- MyBatis介绍及使用
一.介绍: 1.MyBatis实际上是Ibatis3.0版本以后的持久化层框架[也就是和数据库打交道的框架]! 2.和数据库打交道的技术有: 原生的JDBC技术--->Spring的JdbcTe ...
- mybatis介绍安装
MyBatis 是支持定制化 SQL.存储过程以及高级映射的优秀持久层框架.MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集.MyBatis 可以对配置和原生Map使用简单 ...
随机推荐
- 《精通Spring4.X企业应用开发实战》读后感第六章(容器事件)
- BSGS(大小步)算法
BSGS算法主要用于求解形如ax≡b(mod p)的式子中x的值. 在这里我们不妨设 x=k1*n-k2 这时我们就可以将式子转化为 ak1*n≡b*ak2(mod p) 这里的n我们设为√p,所以我 ...
- 12、scala隐式转换与隐式参数
一.隐式转换 1.介绍 Scala提供的隐式转换和隐式参数功能,是非常有特色的功能.是Java等编程语言所没有的功能.它可以允许你手动指定,将某种类型的对象转换成其他类型的对象. 通过这些功能,可以实 ...
- 子元素应该margin-top影响父元素的解决办法
在子元素设置margin-top,有时会带着父元素一起移动. 原因: Outer Div [margin: 0 auto] Inner Div [margin-top: 10px] 根据CSS2.1盒 ...
- android build system resource links
总体结构,参见这里:http://www.jayway.com/2012/10/24/a-practical-approach-to-the-aosp-build-system/ 一般应用的Andro ...
- 使用Django创建一个后端是SQLSERVER的简单系统(一)Django连接SQLServer数据库
window环境下Django连接SQLSERVER, 1.创建项目: 2.创建application: 3.使用pycharm打开项目,如下图: 4.配置虚拟环境: 安装Django\pyodbc\ ...
- JSONCPP开发环境搭建
环境设置 项目地址 https://github.com/open-source-parsers/jsoncpp.git 操作系统 64位 Fedora 24 安装jsoncpp $ git clon ...
- Start and Stop Bitbucket Server
Starting and stopping Bitbucket Server This page describes the various ways you can start or stop Bi ...
- php路径问题
./ 是在当前目录开始寻找文件/ 是在下一级目录开始寻找文件 ../ 这个是在上一级目录开始寻找文件 $_SERVER['DOCUMENT_ROOT']获取站点根目录 __FILE__获取当前文件的完 ...
- Git 2016视频教程
http://blog.csdn.net/biggbang/article/details/50830331