前面三小节内容主要是针对查询操作进行讲解,现在对mybatis增删改进行演示。

由于每次建立工程比较复杂,可以参考第一节:mybatis入门来搭建一个简单的工程,然后来测试本节内容。

1、增


1、新增mapper接口方法,增加一个保存Person对象的方法savePerson。

public interface PersonMapper
{
Boolean savePerson(Person person);
}

2、修改mapper映射文件,添加如下内容:

<insert id="savePerson">
insert into person(first_name,last_name,age,email,address) VALUES(#{firstName},#{lastName},#{age},#{email},#{address})
</insert>

3、测试

public static void main(String[] args)
throws IOException
{
InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
PersonMapper mapper = sqlSession.getMapper(PersonMapper.class);
Person person = new Person();
person.setFirstName("tom");
person.setAge(10);
Boolean isSucceed = mapper.savePerson(person);
sqlSession.commit();
System.out.println(isSucceed);
System.out.println(person);
sqlSession.close();
}

4、结果:

true
Person{id=null, firstName='tom', lastName='null', age=10, email='null', address='null'}

注意:

  • 首先需要执行sqlSession.commit()保证在插入数据时提交事务,另一种方式是在获取SqlSession实例的时候可以加上参数表示自动提交,就不需要手动commit。
SqlSession sqlSession = sqlSessionFactory.openSession(true);
  • 其次打印的person实例的时候,在数据库已经生成了主键id,但是在此打印中却没有获取到,这个就关联到主键如何获取的问题。

5、主键获取

mysql支持自增主键,自增主键值的获取,mybatis是利用statement.getGenreatedKeys();在mapper映射文件进行如下配置即可。
useGeneratedKeys="true":使用自增主键获取主键值策略
keyProperty:指定对应的主键属性,也就是mybatis获取到主键值以后,将这个值封装给javaBean的哪个属性

下面修改mapper映射文件,新增:useGeneratedKeys="true" keyProperty="id",表示使用自增主键获取主键值策略,并且将主键值赋予javaBean的id字段。

<insert id="savePerson" useGeneratedKeys="true" keyProperty="id">
insert into person(first_name,last_name,age,email,address) VALUES(#{firstName},#{lastName},#{age},#{email},#{address})
</insert>

测试结果如下,可以看出id已经有数值。

true
Person{id=19, firstName='tom', lastName='null', age=10, email='null', address='null'}

2、删


1、新增mapper接口方法deletePerson:

public interface PersonMapper
{
Boolean deletePerson(Integer id);
}

2、编写对应的mapper映射文件

<delete id="deletePerson">
delete from person where id = #{id}
</delete>

由于删除操作十分简单,就不过多演示测试过程。

3、改


1、新增mapper接口方法updatePerson:

public interface PersonMapper
{
Boolean updatePerson(Person person);
}

2、编写对应的mapper映射文件

<update id="updatePerson">
update person set first_name = #{firstName} where id = #{id}
</update>

注意:上面的sql语句主要是根据person的id来更新该实例的其它属性,为了演示方便,目前只更新一个firtName字段。

3、测试

public static void main(String[] args)
throws IOException
{
InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
PersonMapper mapper = sqlSession.getMapper(PersonMapper.class);
//首先查询一条数据
Person person = mapper.getPerson(2);
System.out.println(person);
person.setFirstName("tom");
//更新查询的数据的字段
Boolean isSucceed = mapper.updatePerson(person);
sqlSession.commit();
System.out.println(isSucceed);
System.out.println(person);
sqlSession.close();
}

结果如下,可以看出数据已经被更改。

Person{id=2, firstName='King', lastName='Jean', age=36, email='Jean@163.com', address='beijing'}
true
Person{id=2, firstName='tom', lastName='Jean', age=36, email='Jean@163.com', address='beijing'}

4、总结


1、增删改可以在接口方法中定义返回值:Integer、Long、Boolean、void;

2、其次使用sqlSessionFactory.openSession()获取SqlSession需要自动提交。当然如果SqlSession获取使用sqlSessionFactory.openSession(true),则是自动提交,不必手动提交。

3、新增数据可以获取主键,通过useGeneratedKeys="true" keyProperty="id"

4、SQL映射文件有多少标签?

cache –命名空间的二级缓存配置

cache-ref –其他命名空间缓存配置的引用。

resultMap–自定义结果集映射

parameterMap –已废弃!老式风格的参数映射

sql –抽取可重用语句块。

insert –映射插入语句

update –映射更新语句

delete –映射删除语句

select –映射查询语句

mybatis之增删改的更多相关文章

  1. 学习MyBatis必知必会(5)~了解myBatis的作用域和生命周期并抽取工具类MyBatisUtil、mybatis执行增删改查操作

    一.了解myBatis的作用域和生命周期[错误的使用会导致非常严重的并发问题] (1)SqlSessionFactoryBuilder [ 作用:仅仅是用来创建SqlSessionFactory,作用 ...

  2. MyBatis的增删改查。

    数据库的经典操作:增删改查. 在这一章我们主要说明一下简单的查询和增删改,并且对程序接口做了一些调整,以及对一些问题进行了解答. 1.调整后的结构图: 2.连接数据库文件配置分离: 一般的程序都会把连 ...

  3. MyBatis批量增删改查操作

      前文我们介绍了MyBatis基本的增删该查操作,本文介绍批量的增删改查操作.前文地址:http://blog.csdn.net/mahoking/article/details/43673741 ...

  4. 上手spring boot项目(三)之spring boot整合mybatis进行增删改查的三种方式。

    1.引入依赖. <!--springboot的web起步依赖--><dependency> <groupId>org.springframework.boot< ...

  5. 上手spring boot项目(三)之spring boot整合mybatis进行增删改查

    使用mybatis框架进行增删改查大致有两种基础方式,一种扩展方式.两种基础方式分别是使用xml映射文件和使用方法注解.扩展方式是使用mybatis-plus的方式,其用法类似于spring-data ...

  6. 从0开始完成SpringBoot+Mybatis实现增删改查

    1.准备知识: 1)需要掌握的知识: Java基础,JavaWeb开发基础,Spring基础(没有Spring的基础也可以,接触过Spring最好),ajax,Jquery,Mybatis. 2)项目 ...

  7. Spring Boot入门系列(六)如何整合Mybatis实现增删改查

    前面介绍了Spring Boot 中的整合Thymeleaf前端html框架,同时也介绍了Thymeleaf 的用法.不清楚的朋友可以看看之前的文章:https://www.cnblogs.com/z ...

  8. Mybatis实例增删改查(二)

    创建实体类: package com.test.mybatis.bean; public class Employee { private Integer id; private String las ...

  9. mybatis的增删改查返回值小析(六)

    本文验证了通过mybatis访问数据库时的,增删改查的返回值情况. 直接看代码. 1.service层 /** *@Author: Administrator on 2020/3/12 15:15 * ...

随机推荐

  1. 【excel】 超链接相关

    如何导出超链接: 用visual basic处理 在excel中:Alt+F11 --> F7 --> 粘贴下面代码 -->F5(运行), 则会在原列接右侧出现超链  Sub Ext ...

  2. matploylib之热力图

    刚学我也不熟,做个笔记吧 # coding:utf-8 import numpy as np import matplotlib.pyplot as plt dx = 0.01 dy = 0.01 # ...

  3. IDEA compile successfully many errors still occur

    Compile and install successfully with maven in IDEA, but error prompt still popup. Your local enviro ...

  4. MySQL 基础 20191025

    1.MySQL(绿色软件)的安装后: (老师课件中的) 要设置字符集不然会报 1344 错误码,有两种: 为上面的还有一种为: set names 'utf8'; 2.MySQL管理 创建数据库 CR ...

  5. Alpha版本——展示博客【第二组】

    成员简介 章豪 http://cnblogs.com/roar/ 角色: PM,后端 个人介绍: 努力学习开发的小菜鸡,管理小白,背锅组长 贡献: - 设计开发计划 - 跟踪项目进行 - 组织开组会 ...

  6. solrconfig.xml主要配置项

    solrconfig.xml中的配置项主要分以下几大块: 1.依赖的lucene版本配置,这决定了你创建的Lucene索引结构,因为Lucene各版本之间的索引结构并不是完全兼容的,这个需要引起你的注 ...

  7. Python3.5-20190519-廖老师-自我笔记-获取对象信息

    总是优先使用isinstance()判断类型,可以将指定类型及其子类“一网打尽”. 如果要获得一个对象的所有属性和方法,可以使用dir()函数,它返回一个包含字符串的list,比如,获得一个str对象 ...

  8. Java使用SSH远程访问Windows并执行命令

    转载于:http://blog.csdn.net/carolzhang8406/article/details/6760430   https://blog.csdn.net/angel_xiaa/a ...

  9. 一条SQL在 MaxCompute 分布式系统中的旅程

    摘要:2019杭州云栖大会大数据技术专场,由阿里云资深技术专家侯震宇.阿里云高级技术专家陈颖达以及阿里云资深技术专家戴谢宁共同以“SQL在 MaxCompute 分布式系统中的旅程 ”为题进行了演讲. ...

  10. LA 3971 Assemble(二分)

    题目: 给你b元钱,让你组装一台电脑,有n个配件,属性有 种类 名字 价格 品质,每种类型选至少一个,并且最小品质最大.输出这个最大的最小品质. 白书上说了,最小值最大的问题一般是二分来求解答案.在这 ...