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 增删改查操作的更多相关文章

  1. SQL基础语法的单表操作 select|insert|update|delete(增删改查) 简单使用

    以下案列以此表举例 1.select(查询) select简单的查询分为两种 注:字段也就是表结构中的列的名称 第一种: select  字段名  from  表名 此种查询只列出你所需要查询的字段, ...

  2. SQL基础语法select|insert|update|delete(增删改查) 简单使用

    以下案列以此表举例 1.select(查询) select简单的查询分为两种 注:字段也就是表结构中的列的名称 第一种: select  字段名  from  表名 此种查询只列出你所需要查询的字段, ...

  3. mybatis select/insert/update/delete

    这里做了比较清晰的解释: http://mybatis.github.io/mybatis-3/java-api.html SqlSession As mentioned above, the Sql ...

  4. 【Mybatis】mybatis开启Log4j日志、增删改查操作

    Mybatis日志(最常用的Log4j) 官方网站http://www.mybatis.org/mybatis-3/zh/logging.html 1.在src目录下创建一个log4j.propert ...

  5. MyBatis之二:简单增删改查

    这一篇在上一篇的基础上简单讲解如何进行增删改查操作. 一.在mybatis的配置文件conf.xml中注册xml与注解映射 <!-- 注册映射文件 --> <mappers> ...

  6. SpringBoot+Mybatis+Maven+MySQL逆向工程实现增删改查

    SpringBoot+Mybatis+MySQL+MAVEN逆向工程实现增删改查 这两天简单学习了下SpringBoot,发现这玩意配置起来是真的方便,相比于SpringMVC+Spring的配置简直 ...

  7. MyBatis批量增删改查操作

      前文我们介绍了MyBatis基本的增删该查操作,本文介绍批量的增删改查操作.前文地址:http://blog.csdn.net/mahoking/article/details/43673741 ...

  8. 小D课堂-SpringBoot 2.x微信支付在线教育网站项目实战_3-2.使用Mybatis注解开发视频列表增删改查

    笔记 2.使用Mybatis注解开发视频列表增删改查     讲解:使用Mybatis3.x注解方式 增删改查实操, 控制台打印sql语句              1.控制台打印sql语句      ...

  9. MyBatis学习之简单增删改查操作、MyBatis存储过程、MyBatis分页、MyBatis一对一、MyBatis一对多

    一.用到的实体类如下: Student.java package com.company.entity; import java.io.Serializable; import java.util.D ...

随机推荐

  1. sql语句 isnull(列名,'')='' /STUFF的意思

    (1) SELECT  SYXH,ZYHM,YEXH,ISNULL(YETZ,'') AS YETZ ,RYKSMC,RYBQMC,HZXM FROM YG_BRSYK 如果列名数据等于NULL,那么 ...

  2. SQL Fundamentals || Oracle SQL语言

    对于SQL语言,有两个组成部分: DML(data manipulation language) 它们是SELECT.UPDATE.INSERT.DELETE,就象它的名字一样,这4条命令是用来对数据 ...

  3. 基于Docker搭建MySQL主从复制

    摘要: 本篇博文相对简单,因为是初次使用Docker,MySQL的主从复制之前也在Centos环境下搭建过,但是也忘的也差不多了,因此本次尝试在Docker中搭建. 本篇博文相对简单,因为是初次使用D ...

  4. Rabbitmq关于集群节点功能的读书笔记

    消息和队列可以指定是否持久化,如果指定持久化则会保存到硬盘上 ,不然只在内存里 普通集群模式下持久化的队列不能重建了 内存节点和磁盘节点的区别就是将元数据放在了内存还是硬盘,仅此而已,当在集群中声明队 ...

  5. sql 一对多查询

    1. 一对多查询 查询departmentinfo字典下所有部门的人员数量 select * from departmentinfo a left join (select count(*) User ...

  6. 2016年蓝桥杯省赛A组c++第9题(逆序串问题)

    /* X星球的考古学家发现了一批古代留下来的密码. 这些密码是由A.B.C.D 四种植物的种子串成的序列. 仔细分析发现,这些密码串当初应该是前后对称的(也就是我们说的镜像串). 由于年代久远,其中许 ...

  7. wpf之WrapPanel与StackPanel

    WrapPanel: WrapPanel布局面板将各个控件从左至右按照行或列的顺序罗列,当长度或高度不够是就会自动调整进行换行.他有三个属性 Orientation——根据内容自动换行,ItemHei ...

  8. Windows 内存管理

    参考文献: http://blog.csdn.net/wubin1124/article/details/3760242 工作集(内存): 可以这么理解, 此值就是该进程所占用的总物理内存. 但是这个 ...

  9. 在dbgrideh中允许选择多行,如何知道哪些行被选中

    是个BOOKMARK类型的属性. SelectedRows: TBookmarkList procedure TForm1.Button1Click(Sender: TObject); var i, ...

  10. eclipse debug模式

    eclipse debug模式 1.怎样在Eclipse中设置断点 方法/步骤 1 首先打开工程项目 2 第一种是,把鼠标移动想要设置断点的行,在行号前面空白地方双击,就会出现断点 3 第二种是,在菜 ...