MyBatis
-
MyBatis 是一款优秀的持久层框架,用于简化 JDBC 开发
-
持久层:
-
负责将数据保存到数据库的那一层代码
-
JavaEE三层架构:表现层、业务层、持久层
-
-
框架:
-
框架就是一个半成品软件,是一套可重用的、通用的、软件基础代码模型
-
在框架的基础之上构建软件编写更加高效、规范、通用、可扩展
-
-
快速入门
package com.wen;
import com.wen.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
/**
* 快速入门
*/
public class MyBatisDemo {
public static void main(String[] args) throws IOException {
// 1、加载mybatis的核心配置文件,获取 SqlSessionFactory
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 2、获取SqlSession对象,用它来执行SQL
SqlSession sqlSession = sqlSessionFactory.openSession();
// 3、执行SQL语句
List<User> uses = sqlSession.selectList("test.selectAll");
System.out.println(uses);
// 4、释放资源
sqlSession.close();
}
}
Mapper 代理开发
-
定义与SQL映射文件同名的Mapper接口,并且将Mapper接口和SQL映射文件放置在同一个目录下
-
设置SQL映射文件的namespace属性为Mapper接口全限定名
-
在 Mapper 接口中定义方法,方法名就是SQL映射文件中sql语句的id,并保持参数类型和返回值类型一致
-
编码
mybatis-config.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>
<!--别名,更方便的找文件-->
<typeAliases>
<package name="com.wen.pojo"/>
</typeAliases>
<!--
environments:配置数据库连接环境信息,可以配置多个environment, 通过default属性切换不同的environment
-->
<environments default="development">
<environment id="development">
<!--事务管理器-->
<transactionManager type="JDBC"/>
<!-- dataSource:数据库连接池 -->
<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="0221"/>
</dataSource>
</environment>
</environments>
<!--映射器-->
<mappers>
<!--加载SQL映射文件-->
<!--<mapper resource="com/wen/mapper/UserMapper.xml"/>-->
<!--Mapper 代理方式-->
<package name="com.wen.mapper"/>
</mappers>
</configuration>
BrandMapper.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">
<!--
namespace:名称空间
-->
<mapper namespace="com.wen.mapper.BrandMapper">
<!--
数据库表的字段名称 和 实体类的属性名称 不一样,则不能自动封装数据
* 起别名: 对不一样的列名起别名,让别名和实体类的属性名一样
* 缺点:每次查询都要定义一次别名
* 解决:sql片段
* 缺点:不灵活
* resulMap
1. 定义<resulMap>标签
2. 在<select>标签中,使用resultMap属性替换 resultType 属性
-->
<!--sql片段,起别名-->
<sql id="brand_column">
id, brand_name as brandName, company_name as companyName, ordered, description, status
</sql>
<!--resultMap-->
<!--id: 唯一标识 type: 映射的类型,支持别名-->
<resultMap id="brandRasulMap" type="brand">
<!--<id>: 完成主键字段的映射 <result>: 完成一般字段的映射
column: 表的列名 property: 实体类的属性名-->
<result column="brand_name" property="brandName"/>
<result column="company_name" property="companyName"/>
</resultMap>
<!--方法一-->
<select id="selectAll" resultType="brand">
select <include refid="brand_column" /> from tb_brand;
</select>
<!--方法二-->
<select id="selectAll" resultMap="brandRasulMap">
select *
from tb_brand;
</select>
<!--
* 参数占位符:
1. #{}:会将其替换为 ? ,为了防止SQL注入
2. ${}:拼接SQL,会存在SQL注入问题
* 参数类型: parameterType: 可以省略
* 特殊字符处理:
1. 转义字符: < <
2. CDATA区: CD
<![CDATA[
<
]]>
-->
<select id="selectById" resultMap="brandRasulMap">
select *
from tb_brand
where id = #{id}
</select>
<!--多条件查询,固定的,要全部写入-->
<!--<select id="selectByCondition" resultMap="brandRasulMap">
select *
from tb_brand
where status=#{status}
and company_name like #{companyName}
and brand_name like #{brandName}
</select>-->
<!--
动态多条件查询,不固定的,写多少都行
* if: 条件判断
* test: 逻辑表达式
* 问题: 第一个条件不需要逻辑运算符
* 使用恒等式让所有条件格式都一样
* <where> 标签替换 where 关键字
-->
<select id="selectByCondition" resultMap="brandRasulMap">
select *
from tb_brand
<!-- <where>标签 解决"and"问题-->
<where>
<if test="status != null">
and 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>
</where>
</select>
<!--单条件动态查询-->
<select id="selectByConditionSingle" resultMap="brandRasulMap">
select *
from tb_brand
<where>
<choose><!--相当于switch-->
<when test="status != null"><!--相当于case-->
status=#{status}
</when>
<when test="companyName != null and companyName != ''"><!--相当于case-->
ompany_name like #{companyName}
</when>
<when test="brandName != null and brandName != ''"><!--相当于case-->
brand_name like #{brandName}
</when>
<!--相当于default,因为写<where>便签,所有可以不用写-->
<!--<otherwise>
1 = 1
</otherwise>-->
</choose>
</where>
</select>
<!--添加-->
<!--返回添加数据的主键, 可以查到添加数据的id-->
<insert id="add" useGeneratedKeys="true" keyProperty="id">
insert into tb_brand (brand_name, company_name, ordered, description, status)
values (#{brandName}, #{companyName}, #{ordered}, #{description}, #{status});
</insert>
<!--修改-->
<update id="update">
update tb_brand
<!-- <set> 代替 set -->
<!-- <set>标签 解决","问题 -->
<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 = #{ordered},
</if>
<if test="description != null and companyName != ''">
description = #{description},
</if>
<if test="status != null">
status = #{status}
</if>
</set>
where id = #{id};
</update>
<!--删除单条-->
<delete id="deleteById">
delete
from tb_brand
where id = #{id};
</delete>
<!--批量删除-->
<delete id="deleteByIds">
delete
from tb_brand
<!--
mybatis会将数组参数,封装为一个Map集合
* 默认: array = 数组 即: collection="array"
* 使用@Param注解改变map集合的默认key的名称
接口写: void deleteByIds(@Param("ids")int[] ids);
下面写: collection="ids"
-->
where id in
<foreach collection="ids" item="id" separator="," open="(" close=")">
#{id}
</foreach>
</delete>
</mapper>
BrandMapper
public interface BrandMapper {
/*注解完成增删改查*/
@Select("select * from tb_brand where id = #{id}")
List<Brand> selectAll();
/*
* 1. 散装参数: 如果方法中有多个参数,需要使用@Param("SQL参数占位符名称")
* 2. 对象参数: 对象的属性名称要和参数占位符名称一致
* 3. map集合参数:
*/
int deleteById(int id);
void deleteByIds(@Param("ids")int[] ids);
List<Brand> select(@Param("status")int status, @Param("brandName") String brandName);
List<Brand> selectByCondition(Brand brand);
List<Brand> selectByCondition(Map map);
}
MyBatisTest
@Test
public void selectByConditionSingle() 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、加载mybatis的核心配置文件,获取 SqlSessionFactory
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 2、获取SqlSession对象,用它来执行SQL
SqlSession sqlSession = sqlSessionFactory.openSession();
// 3、获取UserMapper 接口的代理对象
BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
// 对象
List<Brand> brands = brandMapper.selectByConditionSingle(brand);
System.out.println(brands);
// 4、释放资源
sqlSession.close();
}
-
加载mybatis的核心配置文件,获取 SqlSessionFactory
-
重复高,抽取工具类
-
SqlSessionFactoryUtil
package com.wen.util;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
public class SqlSessionFactoryUtil {
private static SqlSessionFactory sqlSessionFactory;
static {
// 静态代码块,只加载一次
try {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSessionFactory getSqlSessionFactory(){
return sqlSessionFactory;
}
}