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
数据库表
课程表,包括语文,英语,数学三条数据
-- ----------------------------
-- Table structure for lecture
-- ----------------------------
DROP TABLE IF EXISTS `lecture`;
CREATE TABLE `lecture` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`lecture_name` varchar(255) NOT NULL COMMENT '课程名',
`note` varchar(255) DEFAULT NULL COMMENT '中文备注',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of lecture
-- ----------------------------
INSERT INTO `lecture` VALUES ('1', 'chinese', '语文');
INSERT INTO `lecture` VALUES ('2', 'math', '数学');
INSERT INTO `lecture` VALUES ('3', 'engilsh', '英语');
学生表,包括王五一条信息
-- ----------------------------
-- Table structure for t_student
-- ----------------------------
DROP TABLE IF EXISTS `t_student`;
CREATE TABLE `t_student` (
`id` int(11) NOT NULL,
`cnname` varchar(255) NOT NULL COMMENT '姓名',
`sex` varchar(255) DEFAULT NULL COMMENT '性别',
`note` varchar(255) DEFAULT NULL COMMENT '备注',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of t_student
-- ----------------------------
INSERT INTO `t_student` VALUES ('1', '王五', '0', '广东省广州');
学生课程成绩表
-- ----------------------------
-- Table structure for student_lecture
-- ----------------------------
DROP TABLE IF EXISTS `student_lecture`;
CREATE TABLE `student_lecture` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`lecture_id` int(11) DEFAULT NULL COMMENT '课程号',
`student_id` int(11) DEFAULT NULL COMMENT '学号',
`grade` varchar(255) DEFAULT NULL COMMENT '分数',
`note` varchar(255) DEFAULT NULL COMMENT '备注',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of student_lecture
-- ----------------------------
INSERT INTO `student_lecture` VALUES ('1', '2', '1', '87', '');
INSERT INTO `student_lecture` VALUES ('2', '1', '1', '76', null);
INSERT INTO `student_lecture` VALUES ('3', '3', '1', '82', null);
学生证表
-- ----------------------------
-- Table structure for t_student_selfcard
-- ----------------------------
DROP TABLE IF EXISTS `t_student_selfcard`;
CREATE TABLE `t_student_selfcard` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`student_id` int(11) DEFAULT NULL COMMENT '学号',
`native` varchar(255) DEFAULT NULL COMMENT '籍贯',
`issue_date` date DEFAULT NULL COMMENT '发证日期',
`end_date` date DEFAULT NULL COMMENT '结束日期',
`note` varchar(255) DEFAULT NULL COMMENT '备注',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of t_student_selfcard
-- ----------------------------
INSERT INTO `t_student_selfcard` VALUES ('1', '1', 'guangzhoushi', '2015-09-12', '2017-06-30', 'postgraduate');
java类
//对应表lectures
public class Lecture {
private Integer id;
private String lectureName;
private String note;
getter,setter,toString方法省略
}
//对应表t_student,这里可发现java类比数据库表多了studentSelfcard,studentLectureList两个字段
public class Student {
private int id;
private String cnname;
private Sex sex;
private String note;
private StudentSelfcard studentSelfcard;
private List<StudentLecture> studentLectureList;
getter,setter,toString方法省略
}
//对应表student_lecture
public class StudentLecture {
private int id;
private Integer studentId;
private Lecture lecture;
private BigDecimal grade;
private String note;
getter,setter,toString方法省略
}
//对应表t_student_selfcard
public class StudentSelfcard {
private int id;
private int studentId;
private String native_;
private Date issueDate;
private Date endDate;
private String note;
getter,setter,toString方法省略
}
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接口
public interface LectureMapper {
//通过id,获得相应课程
public Lecture getLecture(int id);
}
提供与Mapper接口组合的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.gethin.mapper.LectureMapper">
<select id="getLecture" parameterType="int" resultType="com.gethin.po.Lecture">
select
id,lecture_name as lectureName,note from lecture where id=#{id}
</select>
</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代替方案如下。
<?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.gethin.mapper.LectureMapper">
<!-- <select id="getLecture" parameterType="int" resultType="com.gethin.po.Lecture">
select
id,lecture_name as lectureName,note from lecture where id=#{id}
</select>-->
<resultMap id="lectureMap" type="com.gethin.po.Lecture">
<id property="id" column="id"/>
<result property="lectureName" column="lecture_name"/>
<result property="note" column="note"/>
</resultMap>
<select id="getLecture" parameterType="int" resultMap="lectureMap">
select
id,lecture_name,note from lecture where id=#{id}
</select>
</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增加如下配置。
<insert id="saveLecture" parameterType="Lecture" useGeneratedKeys="true" keyProperty="id">
insert into lecture(lecture_name,note) VALUES (#{lectureName},#{note})
</insert>
测试一下:
4.updata和delete元素
update和delete元素比较简单,以上述的lecture表为例,分别展示update和delete。
update 在LectureMapper.xml增加update语句
<update id="updateLecture" parameterType="Lecture">
UPDATE lecture set lecture_name=#{lectureName},note=#{note} where id=#{id}
</update>
测试一下:
delete 在LectureMapper.xml增加delete语句
<delete id="deleteLecture" parameterType="int">
DELETE from lecture where id=#{id}
</delete>
插入和删除都会返回一个整数显示跟新或者删除了几条记录。
以上是关于Mybatis增删改查的主要内容,如果未能解决你的问题,请参考以下文章