前面三小节内容主要是针对查询操作进行讲解,现在对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. python 打印日历

    import calendar as c'''x = c.monthcalendar(2017,11) 使用这个结果打印出日历 s = 1while s <= 7: print('周%d '%( ...

  2. 如何用javascript中的canvas让图片自己旋转

    最近在写一个游戏,想让一个人物随着鼠标在原地旋转 在网上找了找,大都是用css写的,但是我为了长远的利益着想选择使用javascript代码中的canvas来解决绘图问题 其中重要的两个方法: con ...

  3. OSG+Visual Studio2015项目变量设置;

    OSG源码经过CMAKE编译后: 1.配置OSG环境变量: 用户变量的PATH中添加路径 C:\OSG\bin系统变量中添加新变量OSG_FILE_PATH为 C:\OSG\data 2.VS新建项目 ...

  4. A Bite Of React(1)

    react: component and views : produce html abd add them on a page( in the dom) <import React from ...

  5. Python - zipfile 乱码问题解决

    最近使用zipfile进行解包过程中遇到了很不舒服的问题,解包之后文件名是乱码的.下面进行简单总结: 首先,乱码肯定是因为解码方式不一样了,zipfile使用的是utf-8和cp437这两种编码方式, ...

  6. HDU 5125 magic balls(线段树+DP)

    magic balls Time Limit: 6000/3000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total ...

  7. 44.Linked List Cycle II(环的入口节点)

    Level:   Medium 题目描述: Given a linked list, return the node where the cycle begins. If there is no cy ...

  8. SqlServer表名称定义

    每一个数据表 添加一个 扩展 属性:Description  填写表描述. 查看是否所有表都添加的Sql如下: SELECT a.name AS name, g.[value] FROM sys.ta ...

  9. 用python实现批量获取Linux主机简要信息并保存到Excel中 unstable 1.1

    #!/usr/bin/env python3 # -*- coding: utf-8 -*- #filename get_linux_info.py #获取Linux主机的信息 # titles=[' ...

  10. db2 连接数据库与断开数据库

    连接数据库: connect to db_name user db_user using db_pass 断开连接: connect  resetdisconnect current quit是退出交 ...