使用MyBatis进行数据库的CRUD操作有2种方式:一种如之前所说的接口+xml,而另一种是通过对接口上的方法加注解(@Select @Insert @Delete @Update)

但是通常情况下不建议使用注解进行操作,原因在于MyBatis最强大的特性在于其动态sql,若使用注解则无法使用动态sql

因此此处仅仅对注解进行简单的举例

一、注解

<?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.mapper.UsersMapper" ><resultMap id="BaseResultMap" type="com.pojo.Users" ><id column="id" property="id" jdbcType="INTEGER" /><result column="name" property="name" jdbcType="VARCHAR" /><result column="password" property="password" jdbcType="VARCHAR" /></resultMap><sql id="Base_Column_List" >id, name, password</sql><select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >select <include refid="Base_Column_List" />from userswhere id = #{id,jdbcType=INTEGER}</select><update id="updateByPrimaryKeySelective" parameterType="com.pojo.Users" >update users<set ><if test="name != null" >name = #{name,jdbcType=VARCHAR},</if><if test="password != null" >password = #{password,jdbcType=VARCHAR},</if></set>where id = #{id,jdbcType=INTEGER}</update><update id="updateByPrimaryKey" parameterType="com.pojo.Users" >update usersset name = #{name,jdbcType=VARCHAR},password = #{password,jdbcType=VARCHAR}where id = #{id,jdbcType=INTEGER}</update>
</mapper>

UsersMapper.xml

package com.mapper;import org.apache.ibatis.annotations.Select;import com.pojo.Users;public interface UsersMapper {@Select("select id, name, password from users where id = #{id}")Users selectByPrimaryKey(Integer id);int updateByPrimaryKeySelective(Users record);
}

UsersMapper.java

依旧以之前反向生成的UsersMapper为例,为显得简洁些,仅保留了2个方法:selectByPrimaryKey和updateByPrimaryKeySelective

打上注解的方法selectByPrimaryKey,其注解效果和xml中的一致,但updateByPrimaryKeySelective方法却无法打上注解,原因无它,该方法使用了动态sql,而注解中无法使用动态sql

二、接口+xml

为了之后好举例,此处重新创建了一个名为student的表,并反向生成了映射文件和实体类,并进行了些许改动

2.1 创建student表并反向生成映射文件和实体类

sql语句如下:

CREATE TABLE student(id INT PRIMARY KEY identity(1,1), name VARCHAR(20), class VARCHAR(20));

反向生成步骤不再多说

2.2 更改映射文件和实体类

反向生成后会发现实体类Student报错了,点开发现在class处报错——class是java的关键字

所以我们应当将class改成clazz,这样就不会报错了

仅仅更改实体类是不够的,还需将映射xml中对应的字段进行修改

最后对接口及xml进行一定的更改,最终结果如下

package com.mapper;import com.pojo.Student;public interface StudentMapper {//通过id删除学生int deleteById(Integer id);//添加学生int insertStudent(Student record);//通过id查找学生
    Student selectById(Integer id);
}

StudentMapper.java

<?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.mapper.StudentMapper" ><resultMap id="BaseResultMap" type="com.pojo.Student" ><id column="id" property="id" jdbcType="INTEGER" /><result column="name" property="name" jdbcType="VARCHAR" /><result column="class" property="clazz" jdbcType="VARCHAR" /></resultMap><sql id="Base_Column_List" >id, name, class</sql><!-- 通过id查找学生 --><select id="selectById" resultMap="BaseResultMap" parameterType="java.lang.Integer" >select <include refid="Base_Column_List" />from studentwhere id = #{id,jdbcType=INTEGER}</select><!-- 通过id删除学生 --><delete id="deleteById" parameterType="java.lang.Integer" >delete from studentwhere id = #{id,jdbcType=INTEGER}</delete><!-- 添加学生 --><insert id="insertStudent" parameterType="com.pojo.Student" >insert into student (name, class)values (#{name,jdbcType=VARCHAR}, #{clazz,jdbcType=VARCHAR})</insert>
</mapper>

StudentMapper.xml

package com.pojo;public class Student {private Integer id;private String name;private String clazz;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name == null ? null : name.trim();}public String getClazz() {return clazz;}public void setClazz(String clazz) {this.clazz = clazz == null ? null : clazz.trim();}@Overridepublic String toString() {return "Student [id=" + id + ", name=" + name + ", clazz=" + clazz + "]";}
}

Student.java

2.3 对数据库进行CRUD操作

1、首先添加一个学生,代码如下:

package com.test;import java.io.InputStream;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 com.mapper.StudentMapper;
import com.pojo.Student;public class TestInsert {public static void main(String[] args) throws Exception {//mybatis的核心配置文件String resource = "mybatis-config.xml";//使用MyBatis提供的Resources类加载mybatis的配置文件InputStream  is = Resources.getResourceAsStream(resource);//构建SqlSession的工厂SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);//开启SqlSessionSqlSession session = factory.openSession();//通过映射接口执行操作StudentMapper mapper = session.getMapper(StudentMapper.class);//new一个名叫张三 一年1班的学生Student stu = new Student();stu.setName("张三");stu.setClazz("一年1班");try {mapper.insertStudent(stu);//提交
            session.commit();} catch (Exception e){//回滚
            session.rollback();System.out.println("添加失败");} finally {session.close();}System.out.println("添加成功");}}

结果:可以从日志中看到sql语句及传入的参数,最后输出“添加成功”

在数据库里查看下添加的结果:确实多了一条数据

为了之后方便操作,在此可以多添加几条数据:

2、查询指定id的学生,代码如下:

package com.test;import java.io.InputStream;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 com.mapper.StudentMapper;
import com.pojo.Student;public class TestSelect {public static void main(String[] args) throws Exception {//mybatis的核心配置文件String resource = "mybatis-config.xml";//使用MyBatis提供的Resources类加载mybatis的配置文件InputStream  is = Resources.getResourceAsStream(resource);//构建SqlSession的工厂SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);//开启SqlSessionSqlSession session = factory.openSession();//通过映射接口执行操作StudentMapper mapper = session.getMapper(StudentMapper.class);Student student = mapper.selectById(1);System.out.println(student);session.close();}}

结果如下:

3、删除指定id的学生,代码如下:

package com.test;import java.io.InputStream;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 com.mapper.StudentMapper;public class TestDelete {public static void main(String[] args) throws Exception {//mybatis的核心配置文件String resource = "mybatis-config.xml";//使用MyBatis提供的Resources类加载mybatis的配置文件InputStream  is = Resources.getResourceAsStream(resource);//构建SqlSession的工厂SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);//开启SqlSessionSqlSession session = factory.openSession();//通过映射接口执行操作StudentMapper mapper = session.getMapper(StudentMapper.class);try {mapper.deleteById(5);//提交
            session.commit();} catch (Exception e){//回滚
            session.rollback();System.out.println("删除失败");} finally {session.close();}System.out.println("删除成功");}}

结果如下:

现在再看数据库中的数据,发现id为5的学生已经不见了:

4、更改指定id的学生姓名

此时,StudentMapper里并没有update相关的方法,所以需要手动添加方法。现在接口中定义updateStudentById方法,然后在xml中编写相应的节点:使用update节点,id与方法名一致,传入参数类型为Student类,节点内为sql语句

package com.mapper;import com.pojo.Student;public interface StudentMapper {//通过id删除学生int deleteById(Integer id);//添加学生int insertStudent(Student record);//通过id查找学生
    Student selectById(Integer id);//更改指定id学生的姓名int updateStudentById(Student student);
}

StudentMappe.java

<?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.mapper.StudentMapper" ><resultMap id="BaseResultMap" type="com.pojo.Student" ><id column="id" property="id" jdbcType="INTEGER" /><result column="name" property="name" jdbcType="VARCHAR" /><result column="class" property="clazz" jdbcType="VARCHAR" /></resultMap><sql id="Base_Column_List" >id, name, class</sql><!-- 通过id查找学生 --><select id="selectById" resultMap="BaseResultMap" parameterType="java.lang.Integer" >select <include refid="Base_Column_List" />from studentwhere id = #{id,jdbcType=INTEGER}</select><!-- 通过id删除学生 --><delete id="deleteById" parameterType="java.lang.Integer" >delete from studentwhere id = #{id,jdbcType=INTEGER}</delete><!-- 添加学生 --><insert id="insertStudent" parameterType="com.pojo.Student" >insert into student (name, class)values (#{name,jdbcType=VARCHAR}, #{clazz,jdbcType=VARCHAR})</insert><!-- 更改指定id学生的姓名 --><update id="updateStudentById" parameterType="com.pojo.Student">update student set name = #{name} where id = #{id}</update>
</mapper>

StudentMapper.xml

编写测试类,先从数据库中查询获得需要修改的学生信息,再更改其姓名,最后提交

package com.test;import java.io.InputStream;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 com.mapper.StudentMapper;
import com.pojo.Student;public class TestUpdate {public static void main(String[] args) throws Exception {//mybatis的核心配置文件String resource = "mybatis-config.xml";//使用MyBatis提供的Resources类加载mybatis的配置文件InputStream  is = Resources.getResourceAsStream(resource);//构建SqlSession的工厂SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);//开启SqlSessionSqlSession session = factory.openSession();//通过映射接口执行操作StudentMapper mapper = session.getMapper(StudentMapper.class);Student student = mapper.selectById(4);System.out.println(student);student.setName("赵六");try{mapper.updateStudentById(student);//提交
            session.commit();} catch (Exception e){//回滚
            session.rollback();System.out.println("更改失败");}System.out.println("更改成功");session.close();}}

结果和数据库如下:

  5、现更改需求:更改指定id学生所在的班级

又多了一个update的需求,需要再新增一个方法吗?并不需要,只需在updateStudentById方法对应的映射sql中进行更改就可以了,这时就可以用到动态sql了

<!-- 更改指定id学生的姓名 --><update id="updateStudentById" parameterType="com.pojo.Student">update student<set><if test="name != null">name = #{name} ,</if><if test="clazz != null">class = #{clazz} ,</if></set>where id = #{id}</update>

将update节点改为上述,再编写测试类

package com.test;import java.io.InputStream;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 com.mapper.StudentMapper;
import com.pojo.Student;public class TestUpdate {public static void main(String[] args) throws Exception {//mybatis的核心配置文件String resource = "mybatis-config.xml";//使用MyBatis提供的Resources类加载mybatis的配置文件InputStream  is = Resources.getResourceAsStream(resource);//构建SqlSession的工厂SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);//开启SqlSessionSqlSession session = factory.openSession();//通过映射接口执行操作StudentMapper mapper = session.getMapper(StudentMapper.class);Student student = new Student();student.setId(4);student.setClazz("三年1班");System.out.println(student);try{mapper.updateStudentById(student);//提交
            session.commit();} catch (Exception e){//回滚
            session.rollback();System.out.println("更改失败");}System.out.println("更改成功");session.close();}}

先new一个Student,再set它的id和class,此时name为null,执行update操作

可以看见执行的sql为update student SET class = ? where id = ?

如果我们将name的值set为aaa,再看执行的sql语句:

可以看见执行的sql为update student SET name = ? , class = ? where id = ?

这就是动态sql,除了if外,还有choose (when, otherwise),trim (where, set),foreach,这些节点的使用方式与JSTL标签的使用类似

三、动态sql

3.1 if

最简单的节点,只需配置test属性即可,test内为布尔表达式,为true时if语句块中的sql语句才会存在,且不会对sql进行任何变动,因此有时会出现多逗号、and、or、where的情况,通常与对应的节点使用,如set、where等

3.2 choose (when, otherwise)

choose节点下有2个子节点when和otherwise,when节点中有1个属性test,和if的类似

该节点的语法与if...else if...else类似

<choose><when test="表达式1">sql语句1</when><when test="表达式2">sql语句2</when><otherwise>sql语句3</otherwise>
</choose>

例如上述例子,当表达式1为true时,有且仅有sql语句1会被执行,不会有2和3;当表达式1、2都不满足时,就会执行sql语句3

3.3 trim

有4个属性:prefix、suffix、prefixOverrides、suffixOverrides。它可以更灵活地去除多余关键字,可以替代where和set

以2.5中的sql语句为例,可变更如下,效果是一样的:

  <!-- 更改指定id学生的姓名 --><update id="updateStudentById" parameterType="com.pojo.Student">update student<trim prefix="set" suffixOverrides="," suffix="where id = #{id}">    <if test="name != null">name = #{name},</if><if test="clazz != null">class = #{clazz},</if></trim></update>

3.4 foreach

用于迭代一个集合,通常用于in条件,其属性如下:

item:集合名称(传入的变量名)

index:指定迭代次数的名称

collection:必须指定,表示传入的集合是什么类型的

list

array

map-key

open:语句的开始

separator:每次循环的分割符

close:语句的结束

转载于:https://www.cnblogs.com/s1165482267/p/8038590.html

MyBatis学习存档(4)——进行CRUD操作相关推荐

  1. mybatis 一对多_Springboot整合Mybatis实现级联一对多CRUD操作

    在关系型数据库中,随处可见表之间的连接,对级联的表进行增删改查也是程序员必备的基础技能.关于Spring Boot整合Mybatis在之前已经详细写过,不熟悉的可以回顾Spring Boot整合Myb ...

  2. MyBatis学习总结(二)——使用MyBatis对表执行CRUD操作

    上一篇博文MyBatis学习总结(一)--MyBatis快速入门中我们讲了如何使用Mybatis查询users表中的数据,算是对MyBatis有一个初步的入门了,今天讲解一下如何使用MyBatis对u ...

  3. Mybatis框架实现CRUD操作

    Mybatis框架实现CRUD操作 自定义mybatis流程 mybatis基于代理dao的CRUD操作(重点) E:\JAVAworkspace\mybatis_CRUD CRUD中可能遇到的问题: ...

  4. Mybatis_day2_Mybatis的CRUD操作

    Mybatis根据动态代理实现CRUD操作 使用要求: 持久层接口(UserDao)和持久层接口的映射配置必须在相同的包下 持久层映射配置中 mapper 标签的 namespace 属性取值必须是持 ...

  5. 2021年3月8日:MyBatis框架学习笔记02:利用MyBatis实现CRUD操作

    MyBatis框架学习笔记02:利用MyBatis实现CRUD操作 在第一节课中我们在UserMapper.xml里定义了两个查询语句:findById和findAll,对应的在UserMapper接 ...

  6. MyBatis学习总结(2)——使用MyBatis对表执行CRUD操作

    一.使用MyBatis对表执行CRUD操作--基于XML的实现 1.定义sql映射xml文件 userMapper.xml文件的内容如下:

  7. 用于MyBatis CRUD操作的Spring MVC 3控制器

    到目前为止,我们已经为域类" User "创建了CRUD数据库服务,并且还将MyBatis配置与Spring Configuration文件集成在一起. 接下来,我们将使用Spri ...

  8. Mybatis——增删改查(CRUD)操作

    java学习--Mybatis CRUD操作 mybatis是一个可以自定义SQL.存储过程和高级映射的持久层框架.上面这个定义是在百度上抄的,简单来说,Mybatis简化了我们对数据库的一系列操作, ...

  9. mybatis CRUD操作

    mybatis CRUD操作 select select标签是mybatis最常用的标签之一. select语句有很多属性可以详细的配置每一天sql语句. id 命名空间唯一的标识. 接口中的方法名与 ...

最新文章

  1. C语言:随笔10--共用体
  2. 纯真IP库的结构分析及一个查询类
  3. PowerDesigner中NAME和COMMENT的互相转换,需要执行语句
  4. intellij无法输入中文
  5. python基础实例 韦玮 pdf_Python基础实例教程(微课版)
  6. thymealf 高级用法_Thymeleaf
  7. go爬虫和python爬虫_爬虫练手-豆瓣top250(go版以及python版)
  8. win上部署基于openvino2020.2的yolov5算法
  9. python 嵌套类实例_使用dict访问Python中嵌套的类实例
  10. 单片机延时程序分析(汇编详细版)
  11. java我的世界非正常退出_我的世界非正常退出怎么办???
  12. 数据备份技术知识梳理(建议收藏)
  13. JAVA多线程下高并发的处理经验
  14. 一公司C#编程规范v2.0(转)
  15. 撸免费的oracle cloud服务器并使用脚本自动化部署云服务器
  16. 怎么画计算机系统时空图,计算机系统结构中流水线的时空图怎么画
  17. 学计算机平面设计需不需要写生,计算机平面设计专业《素描》课程考试大纲
  18. 什么叫克隆人_什么叫克隆技术?为什么不允许克隆人
  19. 听了老同志的教导:\r \n 到底是什么
  20. Chrome 谷歌浏览器升级之后自动保存账号名和密码不能用了?

热门文章

  1. thinkphp跨库操作代码实例
  2. redis 失效时间单位是秒还是毫秒_Redis有效时间设置及时间过期处理
  3. 信息安全工程师笔记-网络安全风险评估技术原理与应用
  4. Ngnix笔记proxy_set_header设置X-Real-IP(Java获取客户端IP地址)
  5. Qt工作笔记-使用SQL中的LIMIT进行数据分页
  6. Java笔记-重写JsonSerializer中serialize方法使Json中时间戳/1000
  7. Spring Boot中使用模板引擎引用资源
  8. Qt学习笔记-服务器端获取UDP封包源IP地址
  9. Qt工作笔记-Qt文档阅读笔记-setMouseTracking(无需按下移动使得widget获取鼠标位置)
  10. Qt文档阅读笔记-QVariant::value()与qvariant_cast解析及使用