Mybatis增删改查

Posted 孩儿坐栏

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Mybatis增删改查相关的知识,希望对你有一定的参考价值。

Mapper(映射器)是MyBatis最强大的工具,这也是我们使用MyBatis时用的最多的工具。MyBatis是针对映射器构造的SQL构建的轻量级框架,并且通过配置生成对应的JavaBean返回给调用者,而这些配置主要便是映射器。所有的增删改查都是通过映射器来完成的(在工程里面就是各个Mapper.xml)。

  • 1.映射器的主要元素

  • 2.select元素

  • 3.insert元素

  • 4.updata和delete元素

1.映射器的主要元素

映射器的元素主要由下表:

元素名称 描述 备注
select 查询语句,最常用,最复杂的元素 可自定义参数,返回结果集
insert 插入语句 执行后返回一个整数,代表插入的条数
update 更新语句 执行后返回一个整数,代表更新的条数
delete 删除语句 执行后返回一个整数,代表删除的条数
sql 允许定义个sql,然后各个地方引用 例如,一张表名,我们可以一次定义,在多个sql中使用
resultMap 用来描述从结果集中来加载对象,它是最复杂、最强大的元素 它提供映射规则
cache 给定命名空间缓存配置 ———
cache-ref 其他命名空间的缓存配置 ———

通过一个简单的项目来演示各个元素的作用,项目的代码放在gitHub上MyBatisPracitice

  • 数据库表

 
   
   
 
  1. 课程表,包括语文,英语,数学三条数据

  2. -- ----------------------------

  3. -- Table structure for lecture

  4. -- ----------------------------

  5. DROP TABLE IF EXISTS `lecture`;

  6. CREATE TABLE `lecture` (

  7.  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',

  8.  `lecture_name` varchar(255) NOT NULL COMMENT '课程名',

  9.  `note` varchar(255) DEFAULT NULL COMMENT '中文备注',

  10.  PRIMARY KEY (`id`)

  11. ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

  12. -- ----------------------------

  13. -- Records of lecture

  14. -- ----------------------------

  15. INSERT INTO `lecture` VALUES ('1', 'chinese', '语文');

  16. INSERT INTO `lecture` VALUES ('2', 'math', '数学');

  17. INSERT INTO `lecture` VALUES ('3', 'engilsh', '英语');

  18. 学生表,包括王五一条信息

  19. -- ----------------------------

  20. -- Table structure for t_student

  21. -- ----------------------------

  22. DROP TABLE IF EXISTS `t_student`;

  23. CREATE TABLE `t_student` (

  24.  `id` int(11) NOT NULL,

  25.  `cnname` varchar(255) NOT NULL COMMENT '姓名',

  26.  `sex` varchar(255) DEFAULT NULL COMMENT '性别',

  27.  `note` varchar(255) DEFAULT NULL COMMENT '备注',

  28.  PRIMARY KEY (`id`)

  29. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

  30. -- ----------------------------

  31. -- Records of t_student

  32. -- ----------------------------

  33. INSERT INTO `t_student` VALUES ('1', '王五', '0', '广东省广州');

  34. 学生课程成绩表

  35. -- ----------------------------

  36. -- Table structure for student_lecture

  37. -- ----------------------------

  38. DROP TABLE IF EXISTS `student_lecture`;

  39. CREATE TABLE `student_lecture` (

  40.  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',

  41.  `lecture_id` int(11) DEFAULT NULL COMMENT '课程号',

  42.  `student_id` int(11) DEFAULT NULL COMMENT '学号',

  43.  `grade` varchar(255) DEFAULT NULL COMMENT '分数',

  44.  `note` varchar(255) DEFAULT NULL COMMENT '备注',

  45.  PRIMARY KEY (`id`)

  46. ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

  47. -- ----------------------------

  48. -- Records of student_lecture

  49. -- ----------------------------

  50. INSERT INTO `student_lecture` VALUES ('1', '2', '1', '87', '');

  51. INSERT INTO `student_lecture` VALUES ('2', '1', '1', '76', null);

  52. INSERT INTO `student_lecture` VALUES ('3', '3', '1', '82', null);

  53. 学生证表

  54. -- ----------------------------

  55. -- Table structure for t_student_selfcard

  56. -- ----------------------------

  57. DROP TABLE IF EXISTS `t_student_selfcard`;

  58. CREATE TABLE `t_student_selfcard` (

  59.  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',

  60.  `student_id` int(11) DEFAULT NULL COMMENT '学号',

  61.  `native` varchar(255) DEFAULT NULL COMMENT '籍贯',

  62.  `issue_date` date DEFAULT NULL COMMENT '发证日期',

  63.  `end_date` date DEFAULT NULL COMMENT '结束日期',

  64.  `note` varchar(255) DEFAULT NULL COMMENT '备注',

  65.  PRIMARY KEY (`id`)

  66. ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

  67. -- ----------------------------

  68. -- Records of t_student_selfcard

  69. -- ----------------------------

  70. INSERT INTO `t_student_selfcard` VALUES ('1', '1', 'guangzhoushi', '2015-09-12', '2017-06-30', 'postgraduate');

  • java类

 
   
   
 
  1. //对应表lectures

  2. public class Lecture {

  3.    private Integer id;

  4.    private String lectureName;

  5.    private String note;

  6.    getter,setter,toString方法省略

  7. }

  8. //对应表t_student,这里可发现java类比数据库表多了studentSelfcard,studentLectureList两个字段

  9. public class Student {

  10.    private int id;

  11.    private String cnname;

  12.    private Sex sex;

  13.    private String note;

  14.    private StudentSelfcard studentSelfcard;

  15.    private List<StudentLecture> studentLectureList;

  16.    getter,setter,toString方法省略

  17. }

  18. //对应表student_lecture

  19. public class StudentLecture {

  20.    private int id;

  21.    private Integer studentId;

  22.    private Lecture lecture;

  23.    private BigDecimal grade;

  24.    private String note;

  25.    getter,setter,toString方法省略

  26. }

  27. //对应表t_student_selfcard

  28. public class StudentSelfcard {

  29.    private int id;

  30.    private int studentId;

  31.    private String native_;

  32.    private Date issueDate;

  33.    private Date endDate;

  34.    private String note;

  35.    getter,setter,toString方法省略

  36. }

2.select元素

select元素是我们最常用的功能。select元素帮助我们从数据库中读出数据,组装数据给业务人员。在执行select前。我们需要定义参数,可以是简单的参数类型,例如int,float,也可以是复杂的参数类型,如JavaBean,Map等。Select元素的常用属性包括下表。

元素 说明
id 它是和Mapper接口组合起来的,提供给MyBatis调用的
parameterType 传递给sql的参数类型,可以使用类的全类名或者别名
resultType 定义类的全路径,在允许自动匹配的情况下,结果集将通过JavaBean的规范映射。或定义为int,double等参数,不能和resultMap同时使用
resultMap 它是映射集的引用,可以使用resultType或者resultMap的其中一个,resultMap可以给你我们自定义映射规则的机会
fulshCache 它的作用是调用SQL之后,是否要求MyBatis清空之前的缓存
useCache 启动二级缓存的开关,是否要求MyBatis将此次结果缓存
fetchSize 获取记录的总条数

以查询Lecture表为例

  • 先提供LectureMapper接口

 
   
   
 
  1. public interface LectureMapper {

  2. //通过id,获得相应课程

  3. public Lecture getLecture(int id);

  4. }

  • 提供与Mapper接口组合的XML

 
   
   
 
  1. <?xml version="1.0" encoding="UTF-8" ?>

  2. <!DOCTYPE mapper

  3.        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"

  4.        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

  5. <mapper namespace="com.gethin.mapper.LectureMapper">

  6.    <select id="getLecture" parameterType="int" resultType="com.gethin.po.Lecture">

  7.        select

  8.        id,lecture_name as lectureName,note from lecture where id=#{id}

  9.    </select>

  10. </mapper>

(a) id="getLecture" 对应的是LectureMapper对应getLecture(int id)方法
(b) parameterType="int" 对应的是getLecture(int id)方法的int参数. parameterType传递的参数也可以用Map或者JavaBean来传递参数
(c) resultType="com.gethin.po.Lecture" 对应的public Lecture getLecture(int id); 的Lecture参数返回类型.同时也可以采用resultMap来自定义参数。采用resultMap代替方案如下。

 
   
   
 
  1. <?xml version="1.0" encoding="UTF-8" ?>

  2. <!DOCTYPE mapper

  3.        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"

  4.        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

  5. <mapper namespace="com.gethin.mapper.LectureMapper">

  6. <!--    <select id="getLecture" parameterType="int" resultType="com.gethin.po.Lecture">

  7.        select

  8.        id,lecture_name as lectureName,note from lecture where id=#{id}

  9.    </select>-->

  10.    <resultMap id="lectureMap" type="com.gethin.po.Lecture">

  11.        <id property="id" column="id"/>

  12.        <result property="lectureName" column="lecture_name"/>

  13.        <result property="note" column="note"/>

  14.    </resultMap>

  15.    <select id="getLecture" parameterType="int" resultMap="lectureMap">

  16.        select

  17.        id,lecture_name,note from lecture where id=#{id}

  18.    </select>

  19. </mapper>

在简单的情况下,我们可以使用resultType通过自动映射完成,这样配置工作会大大减少。resultMap一般用于复杂的级联这些关联的配置。

3.insert元素

insert元素,相对于select元素来说要简单许多。MyBatis会在执行之后返回整数,以表示你进行操作后插入数。insert元素的常用属性有

属性名称 描述
id 它是和Mapper接口组合起来的,提供给MyBatis调用的
parameterType 传递给sql的参数类型,可以使用类的全类名或者别名
fulshCache 它的作用是调用SQL之后,是否要求MyBatis清空之前的缓存
useGeneratedKeys 是否自增主键
keyProperty 表示哪个列作为属性的主键。不能和keyColumn同时使用,只接受整形参数
keyColumn 指明第几个列是主键,不能和keyProperty同时使用

关于主键自增字段,可以通过keyProperty属性指定哪个字段,同时使用useGeneratedKeys属性告诉MyBatis这个主键是否使用数据库内置策略生成。可以在LectureMapper.xml增加如下配置。

 
   
   
 
  1.    <insert id="saveLecture" parameterType="Lecture" useGeneratedKeys="true" keyProperty="id">

  2.        insert into lecture(lecture_name,note) VALUES (#{lectureName},#{note})

  3.    </insert>

测试一下:

4.updata和delete元素

update和delete元素比较简单,以上述的lecture表为例,分别展示update和delete。

  • update 在LectureMapper.xml增加update语句

 
   
   
 
  1.    <update id="updateLecture" parameterType="Lecture">

  2.        UPDATE lecture set lecture_name=#{lectureName},note=#{note} where id=#{id}

  3.    </update>

测试一下:

  • delete 在LectureMapper.xml增加delete语句

 
   
   
 
  1.    <delete id="deleteLecture" parameterType="int">

  2.        DELETE from lecture where id=#{id}

  3.    </delete>

插入和删除都会返回一个整数显示跟新或者删除了几条记录。


以上是关于Mybatis增删改查的主要内容,如果未能解决你的问题,请参考以下文章

Mybatis实现增删改查

Mybatis增删改查

Maven+Mybatis实现数据库增删改查

mybatis之增删改查

[mybatis]快速搭建一个mybatis程序,实现对数据的增删改查

mybatis生成的增删改查怎么用