MyBatis基础:MyBatis数据基本操作(2)
1. MyBatis映射器
2. MyBatis数据基本操作
示例项目结构:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>libing</groupId>
<artifactId>com-helloworld-api</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>com-helloworld-api Maven Webapp</name>
<url>http://maven.apache.org</url> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties> <dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.43</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.0-b07</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<finalName>com-helloworld-api</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
pom.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>
<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://localhost:3306/helloworld?characterEncoding=utf-8" />
<property name="username" value="root" />
<property name="password" value="root" />
</dataSource>
</environment>
</environments> <mappers>
<mapper resource="mappers/RoleMapper.xml" />
</mappers>
</configuration>
mybatis-config.xml
package com.libing.helloworld.model;
public class Role {
private Integer id;
private String roleName;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
}
Role.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.libing.helloworld.dao.IRoleDao">
<resultMap id="baseResultMap" type="com.libing.helloworld.model.Role">
<id property="id" column="id" />
<result property="roleName" column="role_name" />
</resultMap> <select id="findAll" resultMap="baseResultMap">
SELECT
id,
role_name
FROM
role
ORDER BY id ASC
</select> <select id="findBySearchText" resultMap="baseResultMap">
SELECT
id,
role_name
FROM
role
WHERE
role_name LIKE CONCAT(CONCAT('%',#{searchText,jdbcType=VARCHAR}),'%')
ORDER BY id ASC
</select> <select id="findById" resultMap="baseResultMap">
SELECT
id,
role_name
FROM
role
WHERE id = #{id}
</select> <insert id="insert" useGeneratedKeys="true" keyProperty="id" parameterType="com.libing.helloworld.model.Role">
INSERT role
(
role_name
)
VALUES
(
#{roleName}
)
</insert> <update id="update" parameterType="com.libing.helloworld.model.Role">
UPDATE role
SET
role_name=#{roleName}
WHERE
id = #{id}
</update> <delete id="deleteById">
DELETE FROM role
WHERE
id = #{id}
</delete> <delete id="deleteByIds" parameterType="java.util.List">
DELETE FROM role
WHERE
id IN
<foreach collection="list" index="index" item="item" open="(" separator="," close=")">
#{item}
</foreach>
</delete>
</mapper>
RoleMapper.xml
package com.libing.helloworld.test; import java.io.InputStream;
import java.util.ArrayList;
import java.util.List; import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test; import com.libing.helloworld.dao.IRoleDao;
import com.libing.helloworld.model.Role; public class RoleTest {
SqlSession sqlSession = null; @Before
public void init() {
String resource = "mybatis-config.xml";
InputStream inputStream = RoleTest.class.getClassLoader().getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
sqlSession = sqlSessionFactory.openSession();
} @Test
public void findAll() {
try {
IRoleDao roleDao = sqlSession.getMapper(IRoleDao.class);
List<Role> roles = roleDao.findAll(); Assert.assertNotNull(roles);
Assert.assertTrue(roles.size() > 0);
} catch (Exception e) {
e.printStackTrace();
} finally {
sqlSession.close();
}
} @Test
public void findById() {
try {
IRoleDao roleDao = sqlSession.getMapper(IRoleDao.class);
Role role = roleDao.findById(1); Assert.assertNotNull(role);
Assert.assertNotNull(role.getRoleName());
} catch (Exception e) {
e.printStackTrace();
} finally {
sqlSession.close();
}
} @Test
public void insert() {
try {
IRoleDao roleDao = sqlSession.getMapper(IRoleDao.class); Role role = new Role();
role.setRoleName("测试");
int result = roleDao.insert(role); // 只插入一条记录
Assert.assertEquals(1, result);
// id不为null
Assert.assertNotNull(role.getId());
} catch (Exception e) {
e.printStackTrace();
} finally {
sqlSession.rollback();
sqlSession.close();
}
} public void Update() {
try {
IRoleDao roleDao = sqlSession.getMapper(IRoleDao.class); Role role = roleDao.findById(1);
Assert.assertNotNull(role); role.setRoleName("测试");
int result = roleDao.update(role); // 只修改一条记录
Assert.assertEquals(1, result); // 修改后的值
Assert.assertEquals("测试", roleDao.findById(1).getRoleName());
} catch (Exception e) {
e.printStackTrace();
} finally {
sqlSession.rollback();
sqlSession.close();
}
} @Test
public void deleteById() {
try {
IRoleDao roleDao = sqlSession.getMapper(IRoleDao.class); Assert.assertNotNull(roleDao.findById(1)); // 调用删除方法
Assert.assertEquals(1, roleDao.deleteById(1));
// 再次查询,判断是否为null
Assert.assertNull(roleDao.findById(1));
} catch (Exception e) {
e.printStackTrace();
} finally {
// 由于sqlSessionFactory.openSession()是不自动提交的,不手动执行sqlSession.commit()不会提交到数据库
sqlSession.rollback();
sqlSession.close();
}
} @Test
public void deleteByIds() {
try {
List<Integer> ids = new ArrayList<Integer>();
ids.add(1);
ids.add(2); IRoleDao roleDao = sqlSession.getMapper(IRoleDao.class);
int result = roleDao.deleteByIds(ids); Assert.assertTrue(result > 0);
} catch (Exception e) {
e.printStackTrace();
} finally {
sqlSession.rollback();
sqlSession.close();
}
}
}
RoleTest.java
package com.libing.helloworld.dao; import java.util.List; import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.SelectKey;
import org.apache.ibatis.annotations.Update; import com.libing.helloworld.model.Role; public interface IRoleDao { @Select("SELECT id,role_name FROM role")
@Results( value = {
@Result(id = true, property = "id", column = "id"),
@Result(property="roleName", column="role_name")
})
List<Role> findAll(); @Select("SELECT id,role_name FROM role WHERE role_name LIKE CONCAT(CONCAT('%',#{searchText}),'%')")
@Results( value = {
@Result(id = true, property = "id", column = "id"),
@Result(property="roleName", column="role_name")
})
List<Role> findBySearchText(@Param("searchText") String searchText); @Select("SELECT id,role_name FROM role WHERE id = #{id}")
@Results( value = {
@Result(id = true, property = "id", column = "id"),
@Result(property="roleName", column="role_name")
})
Role findById(Integer id); @Insert({
"INSERT INTO role(id,role_name)",
" VALUES ",
"(#{id}, #{roleName})"
})
@Options(useGeneratedKeys = true, keyProperty = "id")
@SelectKey(statement="select last_insert_id()", keyProperty = "id", before = false, resultType = int.class)
int insert(Role role); @Update({
"UPDATE role SET ",
"role_name = #{roleName} ",
"WHERE id = #{id}"
})
int update(Role role); @Delete("DELETE FROM role WHERE id = #{id}")
int deleteById(Integer id); int deleteByIds(List<Integer> ids); }
IRoleDao.java
2.1 select
基于XML方式:
<resultMap id="baseResultMap" type="com.libing.helloworld.model.Role">
<id property="id" column="id" />
<result property="roleName" column="role_name" />
</resultMap> <select id="findAll" resultMap="baseResultMap">
SELECT
id,
role_name
FROM
role
ORDER BY id ASC
</select>
基于注解方式:
@Select("SELECT id,role_name FROM role")
@Results( value = {
@Result(id = true, property = "id", column = "id"),
@Result(property="roleName", column="role_name")
})
List<Role> findAll();
单元测试:
@Test
public void findAll() {
try {
IRoleDao roleDao = sqlSession.getMapper(IRoleDao.class);
List<Role> roles = roleDao.findAll(); Assert.assertNotNull(roles);
Assert.assertTrue(roles.size() > 0);
} catch (Exception e) {
e.printStackTrace();
} finally {
sqlSession.close();
}
}
XML中大于符号与小于符号转义:
> >
< <
或使用 <![CDATA[ ]]>
<select id="findAll" resultMap="baseResultMap">
SELECT
id,
role_name
FROM
role
WHERE id >= 10
ORDER BY id ASC
</select>
<select id="findAll" resultMap="baseResultMap">
SELECT
id,
role_name
FROM
role
WHERE id <![CDATA[>=]]> 10
ORDER BY id ASC
</select>
Role findById(Integer id);
<select id="findById" resultMap="baseResultMap">
SELECT
id,
role_name
FROM
role
WHERE
id = #{id}
</select>
@Test
public void findById() {
try {
IRoleDao roleDao = sqlSession.getMapper(IRoleDao.class);
Role role = roleDao.findById(1); Assert.assertNotNull(role);
Assert.assertNotNull(role.getRoleName());
} catch (Exception e) {
e.printStackTrace();
} finally {
sqlSession.close();
}
}
@Select("SELECT id,role_name FROM role WHERE id = #{id}")
@Results( value = {
@Result(id = true, property = "id", column = "id"),
@Result(property="roleName", column="role_name")
})
Role findById(Integer id);
传递多个参数:
1>. 使用Map传递参数
List<Role> findByMap(Map<String, String> params);
<select id="findByMap" parameterType="map" resultMap="baseResultMap">
SELECT
id,
role_name
FROM
role
WHERE
id != #{id}
AND
role_name = #{roleName}
</select>
@Test
public void findByMap() {
try {
Map<String, String> params = new HashMap<String, String>();
params.put("id", "1");
params.put("roleName", "管理员");
IRoleDao roleDao = sqlSession.getMapper(IRoleDao.class);
List<Role> roles = roleDao.findByMap(params); Assert.assertNotNull(roles);
Assert.assertTrue(roles.size() > 0);
} catch (Exception e) {
e.printStackTrace();
} finally {
sqlSession.close();
}
}
2>. 使用注解方式传递参数
import org.apache.ibatis.annotations.Param;
List<Role> findByAnnotation(@Param("id") Integer id, @Param("roleName") String roleName);
<select id="findByAnnotation" resultMap="baseResultMap">
SELECT
id,
role_name
FROM
role
WHERE
id != #{id}
AND
role_name = #{roleName}
</select>
3>. 使用JavaBean传递参数
package com.libing.helloworld.params;
public class RoleParam {
private Integer id;
private String roleName;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
}
RoleParam.java
List<Role> findByRoleParam(RoleParam params);
<select id="findByRoleParam" parameterType="com.libing.helloworld.params.RoleParam" resultMap="baseResultMap">
SELECT
id,
role_name
FROM
role
WHERE
id != #{id}
AND
role_name = #{roleName}
</select>
传递多个参数总结:
◊ 使用Map方式:Map扩展和维护困难,在实际应用中废弃这种传递参数方式。
◊ 使用@Param注解方式:参数个数<=5时是最佳的传参方式。
◊ JavaBean方式:当参数个数大于5个时,建议使用JavaBean方式。
2.2 insert
MyBatis在执行Insert语句之后返回一个整数,表示插入的记录数。
int insert(Role role);
<insert id="insert" useGeneratedKeys="true" keyProperty="id" parameterType="com.libing.helloworld.model.Role">
INSERT role
(
role_name
)
VALUES
(
#{roleName}
)
</insert>
其中,useGeneratedKeys:配置MyBatis使用JDBC的getGeneratedKeys()来获取由数据库内部生成的主键值,keyProperty:指定主键字段。
@Test
public void insert() {
try {
IRoleDao roleDao = sqlSession.getMapper(IRoleDao.class); Role role = new Role();
role.setRoleName("测试");
int result = roleDao.insert(role); // 只插入一条记录
Assert.assertEquals(1, result);
// id不为null
Assert.assertNotNull(role.getId());
} catch (Exception e) {
e.printStackTrace();
} finally {
sqlSession.rollback();
sqlSession.close();
}
}
@Insert({
"INSERT INTO role(id,role_name)",
" VALUES ",
"(#{id}, #{roleName})"
})
@Options(useGeneratedKeys = true, keyProperty = "id")
@SelectKey(statement="select last_insert_id()", keyProperty = "id", before = false, resultType = int.class)
int insert(Role role);
2.3 update
MyBatis在执行update语句之后返回一个整数,表示更新的记录数。
int update(Role role);
<update id="update" parameterType="com.libing.helloworld.model.Role">
UPDATE role
SET
role_name = #{roleName}
WHERE
id = #{id}
</update>
@Test
public void Update() {
try {
IRoleDao roleDao = sqlSession.getMapper(IRoleDao.class); Role role = roleDao.findById(1);
Assert.assertNotNull(role); role.setRoleName("测试");
int result = roleDao.update(role); // 只修改一条记录
Assert.assertEquals(1, result); // 修改后的值
Assert.assertEquals("测试", roleDao.findById(1).getRoleName());
} catch (Exception e) {
e.printStackTrace();
} finally {
sqlSession.rollback();
sqlSession.close();
}
}
@Update({
"UPDATE role SET ",
"role_name = #{roleName} ",
"WHERE id = #{id}"
})
int update(Role role);
2.4 delete
MyBatis在执行delete语句之后返回一个整数,表示删除的记录数。
int deleteById(Integer id);
<delete id="deleteById">
DELETE FROM role
WHERE
id = #{id}
</delete>
@Test
public void deleteById() {
try {
IRoleDao roleDao = sqlSession.getMapper(IRoleDao.class); Assert.assertNotNull(roleDao.findById(1)); // 调用删除方法
Assert.assertEquals(1, roleDao.deleteById(1));
// 再次查询,判断是否为null
Assert.assertNull(roleDao.findById(1));
} catch (Exception e) {
e.printStackTrace();
} finally {
// 由于sqlSessionFactory.openSession()是不自动提交的,不手动执行sqlSession.commit()不会提交到数据库
sqlSession.rollback();
sqlSession.close();
}
}
@Delete("DELETE FROM role WHERE id = #{id}")
int deleteById(Integer id);
删除多条记录:
int deleteByIds(List<Integer> ids);
<delete id="deleteByIds" parameterType="java.util.List">
DELETE FROM role
WHERE
id IN
<foreach collection="list" index="index" item="item" open="("
separator="," close=")">
#{item}
</foreach>
</delete>
@Test
public void deleteByIds() {
try {
List<Integer> ids = new ArrayList<Integer>();
ids.add(1);
ids.add(2); IRoleDao roleDao = sqlSession.getMapper(IRoleDao.class);
int result = roleDao.deleteByIds(ids); Assert.assertTrue(result > 0);
} catch (Exception e) {
e.printStackTrace();
} finally {
sqlSession.rollback();
sqlSession.close();
}
}
MyBatis基础:MyBatis数据基本操作(2)的更多相关文章
- MyBatis基础入门《十三》批量新增数据
MyBatis基础入门<十三>批量新增数据 批量新增数据方式1:(数据小于一万) xml文件 接口: 测试方法: 测试结果: =============================== ...
- MyBatis基础入门《十二》删除数据 - @Param参数
MyBatis基础入门<十二>删除数据 - @Param参数 描述: 删除数据,这里使用了@Param这个注解,其实在代码中,不使用这个注解也可以的.只是为了学习这个@Param注解,为此 ...
- MyBatis基础入门《十 一》修改数据
MyBatis基础入门<十 一>修改数据 实体类: 接口类: xml文件: 测试类: 测试结果: 数据库: 如有问题,欢迎纠正!!! 如有转载,请标明源处:https://www.cnbl ...
- MyBatis基础入门《十》添加数据
MyBatis基础入门<十>添加数据 描述: 修改了实体类:TblClient.java,将其字段:cbirthday 由String类型改成了Date类型. TblClient.java ...
- Mybatis入门 Mybatis存在的意义 解决的问题 基本操作
Mybatis入门 Mybatis的作用 解决的问题 基本操作 为什么要学MyBatis 我们链接操作数据库需要做的步骤 package Test; import java.sql.*; public ...
- JAVA之Mybatis基础入门--框架搭建与简单查询
JAVA中,操作数据库有JDBC.hibernate.Mybatis等技术,今天整理了下,来讲一讲下Mybatis.也为自己整理下文档: hibernate是一个完全的ORM框架,是完全面向对象的.但 ...
- mybatis基础系列(四)——关联查询、延迟加载、一级缓存与二级缓存
关本文是Mybatis基础系列的第四篇文章,点击下面链接可以查看前面的文章: mybatis基础系列(三)——动态sql mybatis基础系列(二)——基础语法.别名.输入映射.输出映射 mybat ...
- mybatis基础系列(一)——mybatis入门
好久不发博客了,写博文的一个好处是能让心静下来,整理下之前学习过的一些知识一起分享,大神路过~ mybatis简介 MyBatis 是一款优秀的持久层框架,它支持定制化 SQL.存储过程以及高级映射. ...
- MyBatis基础入门《十九》动态SQL(set,trim)
MyBatis基础入门<十九>动态SQL(set,trim) 描述: 1. 问题 : 更新用户表数据时,若某个参数为null时,会导致更新错误 2. 分析: 正确结果: 若某个参数为nul ...
随机推荐
- 【angularjs】使用angularjs模拟淘宝首页-淘宝头条滚动效果
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...
- rman list 命令列举
转 在使用RMAN备份.还原的过程中,我们经常需要查看备份的一些详细信息,例如,RMAN提供了LIST命令.关于LIST命令的详细信息 可以参考Oracle Database Backup and R ...
- VS2015/Visual Studio快捷键无效问题
0 VS2015快捷键无效问题的解决办法 快捷键的使用可以大大提高编码效率,VS为我们内置了不少的常用快捷键组合,实际使用过程中往往会随着计算机上安装其他软件引起快捷键冲突,导致VS快捷键失效,解决办 ...
- 隐写工具Hydan的安装使用方法
Hydan是可以在32位ELF二进制文件里隐藏信息的工具,主要原理是利用了i386指令中的冗余信息. 官网地址:http://www.crazyboy.com/hydan/ 但这个工具最后更新好像是在 ...
- Java网络编程中异步编程的理解
目录 前言 一.异步,同步,阻塞和非阻塞的理解 二.异步编程从用户层面和框架层面不同角度的理解 用户角度的理解 框架角度的理解 三.为什么使用异步 四.理解这些能在实际中的应用 六.困惑 参考文章 前 ...
- 【原创】一个线程oom,进程里其他线程还能运行吗?
引言 这题是一个网友@大脸猫爱吃鱼给我的提问,出自今年校招美团三面的一个真题.大致如下 一个进程有3个线程,如果一个线程抛出oom,其他两个线程还能运行么? 先说一下答案,答案是还能运行 不瞒大家说, ...
- SQL Server 分析函数和排名函数
分析函数基于分组,计算分组内数据的聚合值,经常会和窗口函数OVER()一起使用,使用分析函数可以很方便地计算同比和环比,获得中位数,获得分组的最大值和最小值.分析函数和聚合函数不同,不需要GROUP ...
- java 日志框架总结
在项目开发过程中,我们可以通过 debug 查找问题.而在线上环境我们查找问题只能通过打印日志的方式查找问题.因此对于一个项目而言,日志记录是一个非常重要的问题.因此,如何选择一个合适的日志记录框架也 ...
- c++_work
while((ch=getopt(argc, argv, "X:Y:C:")) != EOF) { switch((char)ch) { case 'X': strcpy(strS ...
- Python全栈开发之路 【第一篇】:Python 介绍
本节内容 一.Python介绍 python的创始人为荷兰人——吉多·范罗苏姆(Guido van Rossum).1989年的圣诞节期间,吉多·范罗苏姆为了在阿姆斯特丹打发时间,决心开发一个新的脚本 ...