MyBatis
一.MyBatis 简介
1.什么是 MyBatis
MyBatis 是一款优秀的持久层框架,用于简化 JDBC 开发
MyBatis 本是 Apache 的一个开源项目 iBatis,2010 年这个项目由 apache softwarefoundation 迁移到了 google code,并且改名为 MyBatis。2013 年 11 月迁移到 Github
官网:https://mybatis.org/mybatis-3/zh/index.html
2.持久层
负责将数据到保存到数据的那一层代码
JavaEE 三层架构:表现层、业务层、持久层
3.框架
二.MyBatis 简化
1.JDBC 缺点
1.硬编码
注册驱动,获取连接 SQL 语句
2.操作繁琐
手动设置参数手动封装结果集
//1.注册驱动Class.forName("com.mysql.jdbc.Driver");//2.获取Connection.连接String url = "jdbc:mysql:///db1?useSSL=false";String uname "root";String pwd ="1234";Connection conn = DriverManager.getConnection(url,uname,pwd);∥接收输入的查询条件String gender="男";∥定义sqlString sql "select from tb_user where gender = ?";∥获取pstmt对象PreparedStatement pstmt = conn.prepareStatement(sql);∥设置?的值pstmt.setString(1,gender);∥执行sqlResultSet rs = pstmt.executeQuery();∥遍历Result,获取数据User user = null;ArrayList<User>users new ArrayList<>();while (rs.next(){∥获取数据 int id rs.getInt("id"); String username = rs.getString("username"); String password = rs.getString("password"); ∥创建对象,设置属性值 user = new User(); user.setld(id); user.setUsername(username); user.setPassword(password); user.setGender(gender); ∥装入集合 users.add(user);}
复制代码
MyBatis 免除了几乎所有的 JDBC 代码 以及设置参数和获取结果集的工作
三.MyBatis 快速入门
1.查询 user 表中所有数据
1.创建 user 表,添加数据
2.创建模块,导入坐标
3.编写小 yBatis 核心配置文件->替换连接信息解决硬编码问题
4.编写 SQL 映射文件->统一管理 sq 语句,解决硬编码问题
5.编码
1.定义P0J0类 2.加载核心配置文件,获取SqlSessionFactory对象 3.获取SqlSession对象,执行SQL语句 4.释放资源
复制代码
create database mybatis;use mybatis;
drop table if exists tb_user;
create table tb_user( id int PRIMARY key auto_increment, username varchar(20), password varchar(20), gender char(1), addr varchar(30));
insert into tb_user values(1,'张三','123','男','北京');insert into tb_user values(2,'李四','345','女','上海');insert into tb_user values(3,'王五','567','男','成都');
复制代码
2.解决 SQL 映射文件的警告提示
四.Mapper 代理开发
1.目的
解决原生方式中的硬编码
简化后期执行 SQL
List<User> users = sqlSession. selectList("test.selectAll"); System.out.println(users);
复制代码
//3.获取接口代理对象 UserMapper userMapper = sqlSession.getMapper(UserMapper.class); //4.执行方法,其实就是执行sgL语句 List<User>users = userMapper.selectAll();
复制代码
2.使用 Mapper 代理方式完成入门案例
1.定义与 SQL 映射文件同名的 Mapper 接口,并且将 Mapper 接口和 SQL 映射文件放置在同一目录下
2.设置 SQL 映射文件的 namespace)属性为 Mapper 接口全限定名
3.在 Mapper 接口中定义方法,方法名就是 SQL 映射文件中 sql 语句的 id,并保持参数类型和返回值类型一致 4.编码
4.1.通过 SqlSession 的 getMapper 方法获取 Mapper 接口的代理对象 4.2.调用对应方法完成 sq 的执行
细节:如果 Mapper 接口名称和 SQL 映射文件名称相同,并在同一目录下,则可以使用包扫描的方式简化 SQL 映射文件的加载
五.MyBatis 核心配置文件
1.environments
配置数据库连接环境信息.可以配置多个 environment,通过不同的 default 属性切换不同的 environment
<environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <!-- 数据库连接信息 --> <property name="driver" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql:///mybatis?useSSL=false"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments>
复制代码
2.mappers
</environments> <mappers> <!-- 加载sql映射文件 --> <mapper resource="com/gbx/mapper/UserMapper.xml"/>
<!-- Mapper代理方式 --> <package name="com.gbx.mapper"/> </mappers>
复制代码
3.typeAliases
类型别名可为 Java 类型设置一个缩写名字。它仅用于 XML 配置,意在降低冗余的全限定类名书写。
<typeAliases> <package name="com.gbx.pojo"/> </typeAliases>
复制代码
六.MyBatis 完成 CURD
查询
添加
修改
删除
1.通过配置 xml 文件
1.1 准备环境
数据库表 tb_ brand 实体类 Brand 测试用例 安装 MyBatisX:插件
#删除tb_brand表drop table if exists tb_brand;#创建tb_brand表create table tb_brand( #id 主键 id int primary key auto_increment, # 品牌名称 brand_name varchar(20), # 企业名称 company_name varchar(20), #排序字段 ordered int, # 描述信息 description varchar(100), #状态: 0 :禁用 1: 启动 status int);insert into tb_brand(brand_name,company_name,ordered,description,status)values('三只松鼠','三只松鼠股份有限公司',5,'好吃不上火',0), ('华为','华为技术有限公司',100,'华为致力于把数字世界带入每个人、每个家庭、每个组织,构建万物互联的智能世界',1), ('小米','小米科技有限公司',50,'are you ok',1);select * from tb_brand;
复制代码
@Datapublic class Brand { //id 主键 private Integer id; //品牌名称 private String brandName; //企业名称 private String companyName; //排序字段 private Integer ordered; //描述信息 private String description; //状态:0:禁用1:启用 private Integer status;}
复制代码
1.2MyBatisX
MyBatisX 是一款基于 IDEA 的快速开发插件,为效率而生。
主要功能:
XML 和接口方法相互跳转
根据接口方法生成 statement
1.3 查询
查询所有
1.编写接口方法:Mapper 接口
2.编写 SQL 语句:SQL 映射文件:3.执行方法,测试
public interface BrandMapper { /** * 查询所有 */ public List<Brand> selectAll();}
复制代码
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "https://mybatis.org/dtd/mybatis-3-mapper.dtd"><!--namespace:名称空间--><mapper namespace="com.gbx.mapper.BrandMapper"> <select id="selectAll" resultType="brand"> select * from tb_brand; </select></mapper>
复制代码
public class MyBatisTest { @Test public void testSelectAll() throws IOException { //1.获取SqlSessionFactory String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //2.获取SqlSession对象 SqlSession sqlSession = sqlSessionFactory.openSession(); //3.获取Mapper接口的代理对象 BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class); //4.执行方法 List<Brand> brands = brandMapper.selectAll(); System.out.println(brands); //5.释放资源 sqlSession.close();
}}
复制代码
MyBatis 完成操作需要几步?三步:编写接口方法>>编写>>执行方法
实体类属性名和数据库表列名不一致,不能自动封装数据 1)起别名:在 SQL 语句中,对不一样的列名起别名,别名和实体类属性名一样可以定义<sql>片段,提升复用性 2)resultMap:定义<resultMap>完成不一致的属性名和列名的映射
<!-- 数据库表的字段名称 和 实体类的属性名称不一样,则不能自动封装数据 *起别名: 对不一样的列名起别名,让别名和实体类的属性名一样 *缺点:每次查询都要定义一次别名 *解决办法:sql 片段 缺点:不灵活--><select id="selectAll" resultType="com.gbx.pojo.Brand"> select id,brand_name as brandName,company_name as companyName,ordered,description,status from tb_brand;</select>
复制代码
<!-- sql 片段--><sql id="brand_column"> id,brand_name as brandName,company_name as companyName,ordered,description,status</sql><select id="selectAll" resultType="com.gbx.pojo.Brand"> select <include refid="brand_column"/> from tb_brand;</select>
复制代码
<!-- 数据库表的字段名称 和 实体类的属性名称不一样,则不能自动封装数据 *resultMap: 1.定义<resultMap>标签 2.使用resultMap属性替换 resultType属性--><!-- id:唯一标识 type:映射的类型,支持别名 --><resultMap id="brandResultMap" type="brand"> <!-- id:完成主键的映射 column:表的列名 property:实体类的属性名 result:完成一般字符的映射 --> <result column="brand_name" property="brandName"/> <result column="company_name" property="companyName"/></resultMap><select id="selectAll" resultType="brandResultMap"> select * from tb_brand;</select>
复制代码
查看详情
1.编写接口方法:Mapper 接口参数:id 结果:Brand2.编写 SQL 语句:SQL 映射文件 3.执行方法,测试
<!-- *参数占位符: 1.#{}:会将其替换成 ? .为了防止sql注入 2.${}:拼sql 会存在sql注入问题 3.使用时机: *在参数传递的时候: #{} *表明或者列名不固定的情况下:${}会存在sql注入问题 *参数类型:parameterType:可以省略 *特殊字符处理: 1.转义字符: 2.CDATA区 <I[CDATA[内容]> --><select id="selectById" parameterType="int" resultMap="brandResultMap"> select * from tb_brand where id = #{id};</select>
复制代码
条件查询
1.多条件查询
1.编写接口方法:Mapper 接口
参数:所有查询条件 结果:List<Brand>
2.编写 SQL 语句:SQL 映射文件 3.执行方法,测试
List<Brand> selectByCondition(@Param("status")int status,@Param("companyName") String companyName,@Param("brandName")String brandName);
<select id="selectByCondition" resultType="brandResultMap"> select * from tb_brand where status = #{status} and company_name like #{companyName} and brand_name like #{brandName} </select> @Test public void testSelectByCondition() throws IOException { //接收参数 int status = 1; String companyName = "华为"; String brandName = "华为";
//处理参数 companyName="%"+companyName+"%"; brandName="%"+brandName+"%"; //1.获取SqlSessionFactory String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //2.获取SqlSession对象 SqlSession sqlSession = sqlSessionFactory.openSession(); //3.获取Mapper接口的代理对象 BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class); //4.执行方法 List<Brand> brands = brandMapper.selectByCondition(status, companyName, brandName); System.out.println(brands); //5.释放资源 sqlSession.close(); }
复制代码
List <Brand> selectByCondition(Brand brand);
<select id="selectByCondition" resultType="brandResultMap"> select * from tb_brand where status = #{status} and company_name like #{companyName} and brand_name like #{brandName} </select> @Test public void testSelectByCondition() throws IOException { //接收参数 int status = 1; String companyName = "华为"; String brandName = "华为";
//处理参数 companyName="%"+companyName+"%"; brandName="%"+brandName+"%";
//封装对象 Brand brand = new Brand(); brand.setStatus(status); brand.setCompanyName(companyName); brand.setBrandName(brandName); //1.获取SqlSessionFactory String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //2.获取SqlSession对象 SqlSession sqlSession = sqlSessionFactory.openSession(); //3.获取Mapper接口的代理对象 BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class); //4.执行方法 List<Brand> brands = brandMapper.selectByCondition(brand); System.out.println(brands); //5.释放资源 sqlSession.close(); }
复制代码
List <Brand> selectByCondition(Map map);
<select id="selectByCondition" resultType="brandResultMap"> select * from tb_brand where status = #{status} and company_name like #{companyName} and brand_name like #{brandName} </select> @Test public void testSelectByCondition() throws IOException { //接收参数 int status = 1; String companyName = "华为"; String brandName = "华为";
//处理参数 companyName="%"+companyName+"%"; brandName="%"+brandName+"%";
//Map集合 Map map = new HashMap(); map.put("status",status); map.put("companyName",companyName); map.put("brandName",brandName); //1.获取SqlSessionFactory String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //2.获取SqlSession对象 SqlSession sqlSession = sqlSessionFactory.openSession(); //3.获取Mapper接口的代理对象 BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class); //4.执行方法 List<Brand> brands = brandMapper.selectByCondition(map); System.out.println(brands); //5.释放资源 sqlSession.close(); }
复制代码
2.动态查询
SQL 语句会随着用户的输入或外部条件的变化而变化,我们称为动态 SQL
<select id="selectByCondition"resultMap="brandResultMap"> select * from tb_brand where if(status!=null) status =#status) and company name like #{companyName} and brand name like #{brandName)<select>
复制代码
MyBatis 对动态 SQL 有很强大的支撑:
if
choose (when,otherwise)
trim (where,set)
foreach
2.1if 查询
<!-- 动态条件查询 *if:条件判断 *test:逻辑表达式 *问题:第一个条件不需要逻辑运算符 *恒等式 *<where>替换where关键字 --> <select id="selectByCondition" resultType="brandResultMap"> select * from tb_brand where <if test="status!=null"> status = #{status} </if> <if test="companyName!=null and companyName!=''"> and company_name like #{companyName} </if> <if test="brandName!=null and brandName!=''"> and brand_name like #{brandName} </if> </select>
复制代码
2.2choose(when,otherwise)查询
从多个条件中选择个.
类似于 Java 中的 switch 语句
<select id="selectByConditionSingle"resultMap="brandResultMap"> select from tb_brand where <choose><!-类似于switch-> <when test=:"status=nul"><!-类似于case-> status =#{status) </when> <when test="companyName!=null and companyName !=""> company_name like #{companyName} </when> <when test="brandName !null and brandName !="" brand_name like #{brandName} </when> <otherwise><I-类似于default-> 1=1 </otherwise> </choose></select>
复制代码
3.添加
1.编写接口方法:Mapper 接口
2.编写 SQL 语句:SQL 映射文件
3.执行方法,测试
MyBatis 事务:
/** * 添加 */ void add(Brand brand);
复制代码
<insert id="add"> insert into tb_brand (brand_name,company_name,ordered,description,status) values (#{brandName},#{companyName},#{ordered},#{description},#{status}); </insert>
复制代码
<insert id="add"> insert into tb_brand (brand_name,company_name,ordered,description,status) values (#{brandName},#{companyName},#{ordered},#{description},#{status});</insert>
复制代码
@Test public void testAdd() throws IOException { //接收参数 int status = 1; String companyName = "菠萝手机"; String brandName = "菠萝"; String description = "菠萝手机,手机中的战斗机"; int ordered = 100; //封装对象 Brand brand = new Brand(); brand.setStatus(status); brand.setCompanyName(companyName); brand.setBrandName(brandName); brand.setDescription(description); brand.setOrdered(ordered); //1.获取SqlSessionFactory String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //2.获取SqlSession对象 //方式一 SqlSession sqlSession = sqlSessionFactory.openSession(); //方式二 自动提交事务 SqlSession sqlSession = sqlSessionFactory.openSession(true); //3.获取Mapper接口的代理对象 BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class); //4.执行方法 brandMapper.add(brand); //提交事务 sqlSession.commit(); //5.释放资源 sqlSession.close(); }
复制代码
3.1 主键返回
在数据添加成功后,需要获取插入数据库数据的主键的值
1.添加订单
2.添加订单项,订单项中需要设置所属订单的 id
<insert id="add" useGeneratedKey="true" keyProperty="id"> insert into tb_brand (brand_name,company_name,ordered,description,status) values (#{brandName},#{companyName},#{ordered},#{description},#{status});</insert>
复制代码
@Test public void testAdd2() throws IOException { //接收参数 int status = 1; String companyName = "菠萝手机"; String brandName = "菠萝"; String description = "菠萝手机,手机中的战斗机"; int ordered = 100; //封装对象 Brand brand = new Brand(); brand.setStatus(status); brand.setCompanyName(companyName); brand.setBrandName(brandName); brand.setDescription(description); brand.setOrdered(ordered); //1.获取SqlSessionFactory String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //2.获取SqlSession对象 //方式一 SqlSession sqlSession = sqlSessionFactory.openSession(); //方式二 自动提交事务 SqlSession sqlSession = sqlSessionFactory.openSession(true); //3.获取Mapper接口的代理对象 BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class); //4.执行方法 brandMapper.add(brand); Integer id = brand.getId(); System.out.println(id); //提交事务 sqlSession.commit(); //5.释放资源 sqlSession.close(); }
复制代码
返回添加数据的主键<insert useGeneratedKeys="true"keyProperty="id">
4.修改
4.1 修改全部字段
1.编写接口方法:Mapper 接口
2.编写 SQL 语句:SQL 映射文件 3.执行方法,测试
/** * 修改 */ int update(Brand brand);
复制代码
<update id="update"> update tb_brand set brand_name=#{brandName}, company_name=#{companyName}, ordered=#{brandName}, description=#{description}, status=#{status} where id = #{id};</update>
复制代码
@Test public void testUpdate() throws IOException { //接收参数 int status = 1; String companyName = "菠萝手机"; String brandName = "菠萝"; String description = "手机中的战斗机"; int ordered = 200; int id = 5; //封装对象 Brand brand = new Brand(); brand.setStatus(status); brand.setCompanyName(companyName); brand.setBrandName(brandName); brand.setDescription(description); brand.setOrdered(ordered); brand.setId(id); //1.获取SqlSessionFactory String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //2.获取SqlSession对象 //方式一 SqlSession sqlSession = sqlSessionFactory.openSession(); //方式二 自动提交事务 SqlSession sqlSession = sqlSessionFactory.openSession(true); //3.获取Mapper接口的代理对象 BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class); //4.执行方法 int count = brandMapper.update(brand); System.out.println(count); //提交事务 sqlSession.commit(); //5.释放资源 sqlSession.close(); }
复制代码
4.2 修改动态字段
1.编写接口方法:Mapper 接口
2.编写 SQL 语句:SQL 映射文件 3.执行方法,测试
<update id="update"> update tb_brand <set> <if test="brandName !=null and brandName !=''> brand_name=#{brandName}, </if> <if test="companyName !=null and companyName !=''> company_name=#{companyName, </if> <if test="ordered !=null"> ordered=#{fordered}, </if> <if test="description !=null and description !=''> description=#{description}, </if> <if test="status !=null> status=#{status} </if> </set> where id #{id};</update>
复制代码
5.删除
5.1 删除一个
1.编写接口方法:Mapper 接口
2.编写 SQL 语句:SQL 映射文件
3.执行方法,测试
<delete id="deleteById"> delete from tb_brand where id = #{id};</delete>
复制代码
@Test public void testDeleteById() throws IOException { //接收参数 int id = 6;
//1.获取SqlSessionFactory String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //2.获取SqlSession对象 //方式一 SqlSession sqlSession = sqlSessionFactory.openSession(); //方式二 自动提交事务 SqlSession sqlSession = sqlSessionFactory.openSession(true); //3.获取Mapper接口的代理对象 BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class); //4.执行方法 brandMapper.deleteById(id); //提交事务 sqlSession.commit(); //5.释放资源 sqlSession.close(); }
复制代码
5.2 批量删除
1.编写接口方法:Mapper 接口
2.编写 SQL 语句:SQL 映射文件
3.执行方法,测试
void deleteByIds(@Param("ids")int[]ids);
复制代码
mybatis 会将数组参数,封装为一个 Map 集合。*默认:array=数组
*使用 @Param 注解改变 map 集合的默认 key 的名称
<delete id="deleteByIds"> delete from tb_brand where id in <foreach collection="array" separator="," open="(" close=")"> #{id} </foreach> ;</delete>
复制代码
@Test public void testDeleteByIds() throws IOException { //接收参数 int ids = {5,7,8};
//1.获取SqlSessionFactory String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //2.获取SqlSession对象 //方式一 SqlSession sqlSession = sqlSessionFactory.openSession(); //方式二 自动提交事务 SqlSession sqlSession = sqlSessionFactory.openSession(true); //3.获取Mapper接口的代理对象 BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class); //4.执行方法 brandMapper.deleteByIds(ids); //提交事务 sqlSession.commit(); //5.释放资源 sqlSession.close(); }
复制代码
6.MyBatis 参数传递
MyBatis 接口方法中可以接收各种各样的参数,MyBatis 底层对于这些参数进行不同的封装处理方式
单个参数:
1.POO 类型:直接使用,属性名和参数占位符名称一致 2.Map 集合:直接使用,键名和参数占位符名称一到 3.Collection:封装为 Map 集合
map.put("arg0",collection 集合); map.put("collection",collection 集合);
4.List:封装为 Map 集合
map.put("arg0",List 集合): map.put("collection",List 集合); map.put("List",List 集合);
5.Array:封装为 Map 集合
map.put("argo",数组); map.put("array",数组);
6.其他类型:直接使用
多个参数:封装为 Map 集合
map.put("arg0",参数值 1)
map.put("param1",参数值 1)
map.put("param2",参数值 2)
map.put("arg1",参数值 2)
MyBatisj 提供了 ParamNameResolver 类来进行参数封装
User select(String username,String password);
复制代码
<select id="select"resultType="user"> select * from tb_user where username = #{arg0} and password = #{arg1}</select>
复制代码
7.通过注解开发
使用注解开发会比配置文件开发更加方便
@Select("select from tb_user where id =#{id}")public User seectByld(int id);
复制代码
查询:@Select
添加:@Insert
修改:@Update
删除:@Delete
提示:注解完成简单功能配置文件完成复杂功能
使用注解来映射简单语句会使代码显得更加简洁,但对于稍微复杂一点的语句,Java 注解不仅力不从心,还会让你本就复杂的 SQL 语句更加混乱不堪。因此,如果你需要做一些很复杂的操作,最好用 XML 来映射语句 选择何种方式来配置映射,以及认为是否应该要统一映射语句定义的形式,完全取决于你和你的团队。换句话说,永远不要拘泥于一种方式,你可以很轻松的在基于注解和 XML 的语句映射方式间自由移植和切换
评论