Mybatis select、insert、update、delete 增删改查操作
MyBatis 是支持普通 SQL 查询,存储过程和高级映射的优秀持久层框架。 MyBatis 消除了几乎所有的 JDBC 代码和参数的手工设置以及对结果集的检索。MyBatis 可以使用简单的XML 或注解用于配置和原始映射,将接口和 Java 的 POJO(Plain Old Java Objects,普通的Java对象)映射成数据库中的记录。
MyBatis下载:https://github.com/mybatis/mybatis-3/releases
Mybatis实例
对一个User表的CRUD操作:
User表:

-- ----------------------------
-- Table structure for `user`
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`userName` varchar(50) DEFAULT NULL,
`userAge` int(11) DEFAULT NULL,
`userAddress` varchar(200) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8; -- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'summer', '30', 'shanghai');
INSERT INTO `user` VALUES ('2', 'test2', '22', 'suzhou');
INSERT INTO `user` VALUES ('3', 'test1', '29', 'some place');
INSERT INTO `user` VALUES ('4', 'lu', '28', 'some place');
INSERT INTO `user` VALUES ('5', 'xiaoxun', '27', 'nanjing');

在Src目录下建一个mybatis的xml配置文件Configuration.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- mybatis别名定义 -->
<typeAliases>
<typeAlias alias="User" type="com.mybatis.test.User"/>
</typeAliases> <environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis" />
<property name="username" value="root"/>
<property name="password" value="admin"/>
</dataSource>
</environment>
</environments> <!-- mybatis的mapper文件,每个xml配置文件对应一个接口 -->
<mappers>
<mapper resource="com/mybatis/test/User.xml"/>
</mappers>
</configuration>

定义User mappers的User.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.mybatis.test.IUserOperation"> <!-- select语句 -->
<select id="selectUserByID" parameterType="int" resultType="User">
select * from `user` where user.id = #{id}
</select> <!-- 定义的resultMap,可以解决类的属性名和数据库列名不一致的问题-->
<!-- <resultMap type="User" id="userResultMap">
<id property="id" column="user_id" />
<result property="userName" column="user_userName" />
<result property="userAge" column="user_userAge" />
<result property="userAddress" column="user_userAddress" />
</resultMap> --> <!-- 返回list的select语句,注意 resultMap的值是指向前面定义好的 -->
<!-- <select id="selectUsersByName" parameterType="string" resultMap="userResultMap">
select * from user where user.userName = #{userName}
</select> --> <select id="selectUsersByName" parameterType="string" resultType="User">
select * from user where user.userName = #{userName}
</select> <!--执行增加操作的SQL语句。id和parameterType分别与IUserOperation接口中的addUser方法的名字和参数类型一致。
useGeneratedKeys设置为"true"表明要MyBatis获取由数据库自动生成的主键;keyProperty="id"指定把获取到的主键值注入到User的id属性-->
<insert id="addUser" parameterType="User"
useGeneratedKeys="true" keyProperty="id">
insert into user(userName,userAge,userAddress)
values(#{userName},#{userAge},#{userAddress})
</insert> <update id="updateUser" parameterType="User" >
update user set userName=#{userName},userAge=#{userAge},userAddress=#{userAddress} where id=#{id}
</update> <delete id="deleteUser" parameterType="int">
delete from user where id=#{id}
</delete> </mapper>

配置文件实现了接口和SQL语句的映射关系。selectUsersByName采用了2种方式实现,注释掉的也是一种实现,采用resultMap可以把属性和数据库列名映射关系定义好,property为类的属性,column是表的列名,也可以是表列名的别名!
select 语句属性配置细节:
属性 | 描述 | 取值 | 默认 |
---|---|---|---|
id | 在这个模式下唯一的标识符,可被其它语句引用 | ||
parameterType | 传给此语句的参数的完整类名或别名 | ||
resultType | 语句返回值类型的整类名或别名。注意,如果是集合,那么这里填写的是集合的项的整类名或别名,而不是集合本身的类名。(resultType 与resultMap 不能并用) | ||
resultMap | 引用的外部resultMap 名。结果集映射是MyBatis 中最强大的特性。许多复杂的映射都可以轻松解决。(resultType 与resultMap 不能并用) | ||
flushCache | 如果设为true,则会在每次语句调用的时候就会清空缓存。select 语句默认设为false | true/false | false |
useCache | 如果设为true,则语句的结果集将被缓存。select 语句默认设为false | true/false | false |
timeout | 设置驱动器在抛出异常前等待回应的最长时间,默认为不设值,由驱动器自己决定 | 正整数 | 未设置 |
fetchSize | 设置一个值后,驱动器会在结果集数目达到此数值后,激发返回,默认为不设值,由驱动器自己决定 | 正整数 | 驱动器决定 |
statementType | statement,preparedstatement,callablestatement。预准备语句、可调用语句 | STATEMENT、PREPARED、CALLABLE | PREPARED |
resultSetType | forward_only、scroll_sensitive、scroll_insensitive 只转发,滚动敏感,不区分大小写的滚动 | FORWARD_ONLY、SCROLL_SENSITIVE、SCROLL_INSENSITIVE | 驱动器决定 |
useGeneratedKeys | 告诉MyBatis 使用JDBC 的getGeneratedKeys 方法来获取数据库自己生成的主键(MySQL、SQLSERVER 等关系型数据库会有自动生成的字段)。默认:false | true/false | false |
keyProperty | 标识一个将要被MyBatis设置进getGeneratedKeys的key 所返回的值,或者为insert 语句使用一个selectKey子元素。 |
insert:
<!-- 插入学生 -->
<insert id="insertStudent" parameterType="StudentEntity">
INSERT INTO STUDENT_TBL (STUDENT_ID,
STUDENT_NAME,
STUDENT_SEX,
STUDENT_BIRTHDAY,
CLASS_ID)
VALUES (#{studentID},
#{studentName},
#{studentSex},
#{studentBirthday},
#{classEntity.classID})
</insert>
- 1
<!-- 删除学生 --> <delete id="deleteStudent" parameterType="StudentEntity"> DELETE FROM STUDENT_TBL WHERE STUDENT_ID = #{studentID} </delete>
<!-- 查询学生list,根据入学时间 -->
<select id="getStudentListByDate" parameterType="Date" resultMap="studentResultMap">
SELECT *
FROM STUDENT_TBL ST LEFT JOIN CLASS_TBL CT ON ST.CLASS_ID = CT.CLASS_ID
WHERE CT.CLASS_YEAR = #{classYear};
</select>
List<StudentEntity> studentList = studentMapper.getStudentListByClassYear(StringUtil.parse("2007-9-1"));
for (StudentEntity entityTemp : studentList) {
System.out.println(entityTemp.toString());
}
多参数的实现
如果想传入多个参数,则需要在接口的参数上添加@Param注解。给出一个实例:
接口写法:
public List<StudentEntity> getStudentListWhereParam(@Param(value = "name") String name, @Param(value = "sex") String sex, @Param(value = "birthday") Date birthdar, @Param(value = "classEntity") ClassEntity classEntity);
<!-- 查询学生list,like姓名、=性别、=生日、=班级,多参数方式 -->
<select id="getStudentListWhereParam" resultMap="studentResultMap">
SELECT * from STUDENT_TBL ST
<where>
<if test="name!=null and name!='' ">
ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{name}),'%')
</if>
<if test="sex!= null and sex!= '' ">
AND ST.STUDENT_SEX = #{sex}
</if>
<if test="birthday!=null">
AND ST.STUDENT_BIRTHDAY = #{birthday}
</if>
<if test="classEntity!=null and classEntity.classID !=null and classEntity.classID!='' ">
AND ST.CLASS_ID = #{classEntity.classID}
</if>
</where>
</select>
https://www.cnblogs.com/luxiaoxun/p/4035040.html
Mybatis select、insert、update、delete 增删改查操作的更多相关文章
- SQL基础语法的单表操作 select|insert|update|delete(增删改查) 简单使用
以下案列以此表举例 1.select(查询) select简单的查询分为两种 注:字段也就是表结构中的列的名称 第一种: select 字段名 from 表名 此种查询只列出你所需要查询的字段, ...
- SQL基础语法select|insert|update|delete(增删改查) 简单使用
以下案列以此表举例 1.select(查询) select简单的查询分为两种 注:字段也就是表结构中的列的名称 第一种: select 字段名 from 表名 此种查询只列出你所需要查询的字段, ...
- mybatis select/insert/update/delete
这里做了比较清晰的解释: http://mybatis.github.io/mybatis-3/java-api.html SqlSession As mentioned above, the Sql ...
- 【Mybatis】mybatis开启Log4j日志、增删改查操作
Mybatis日志(最常用的Log4j) 官方网站http://www.mybatis.org/mybatis-3/zh/logging.html 1.在src目录下创建一个log4j.propert ...
- MyBatis之二:简单增删改查
这一篇在上一篇的基础上简单讲解如何进行增删改查操作. 一.在mybatis的配置文件conf.xml中注册xml与注解映射 <!-- 注册映射文件 --> <mappers> ...
- SpringBoot+Mybatis+Maven+MySQL逆向工程实现增删改查
SpringBoot+Mybatis+MySQL+MAVEN逆向工程实现增删改查 这两天简单学习了下SpringBoot,发现这玩意配置起来是真的方便,相比于SpringMVC+Spring的配置简直 ...
- MyBatis批量增删改查操作
前文我们介绍了MyBatis基本的增删该查操作,本文介绍批量的增删改查操作.前文地址:http://blog.csdn.net/mahoking/article/details/43673741 ...
- 小D课堂-SpringBoot 2.x微信支付在线教育网站项目实战_3-2.使用Mybatis注解开发视频列表增删改查
笔记 2.使用Mybatis注解开发视频列表增删改查 讲解:使用Mybatis3.x注解方式 增删改查实操, 控制台打印sql语句 1.控制台打印sql语句 ...
- MyBatis学习之简单增删改查操作、MyBatis存储过程、MyBatis分页、MyBatis一对一、MyBatis一对多
一.用到的实体类如下: Student.java package com.company.entity; import java.io.Serializable; import java.util.D ...
随机推荐
- Nordic NRF51822 从零开始系列(一)开发环境的搭建
硬件准备 (1)nrf51822 开发板一块(此处使用的是青云系列的,自带jlijnk ob+usb串口芯片)或者使用nrf51822模块+jlink_ob ( ...
- VC++、Win32 SDK、MFC的区别
这是一个初进行开发人员都可能遇到过的概念不清的问题,自己当年也同样有过误解,做技术我感觉一定要专,但是,不代表毫不关心相关的知识,至少概念层次上要知道,所以,这里还是再把这些内容纪录下来,好记性不如烂 ...
- python基础①
一. Python 命名规范: 1, 变量量由字⺟母, 数字,下划线搭配组合⽽而成 2, 不不可以⽤用数字开头,更更不不能是全数字 3,不能是pythond的关键字, 这些符号和字⺟母已经 ...
- 【作业】用栈模拟dfs
题意:一个迷宫,起点到终点的路径,不用递归. 题解: #define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<stdli ...
- page 页 分页 分段
小结: 1. 页:磁盘和内存间传输数据的最小单位: MySQL: What is a page? https://stackoverflow.com/questions/4401910/mysql-w ...
- [network] IPVS / Load balancer / Linux Virtual Server
Load Balancer IPVS: http://kb.linuxvirtualserver.org/wiki/IPVS NAT: http://kb.linuxvirtualserver.org ...
- [troubleshoot][automake] automake编译的时候发生死循环
在某台特有设备上,编译dssl工程时,竟然发生了死循环. https://github.com/tony-caotong/libdssl 错误日志如下: checking zlib.h presenc ...
- [dev][https] 非PFS协商的https的流量的解码
经过基础调研之后,目前准备确认实现方案,完成对https的解码. 之前的调研,传送门: http://www.cnblogs.com/hugetong/p/6670083.html 1. 需求: 以旁 ...
- 转:jquery的$(function(){})和$(document).ready(function(){}) 的区别
原文链接:https://www.cnblogs.com/slyzly/articles/7809935.html [转载]jquery的$(function(){})和$(document).rea ...
- struct和[]byte的转换,注意结构体内变量首字母一定大写
type temp struct { Afd int Bee string }func main(){ text:=temp{3123,"4234"} b._:=j ...