文章目录
Mybatis简介
持久层:负责与数据库交互的那一层代码
JAVAee的项目分为三层:持久层,业务层,表现层
JDBC的缺点:
- 硬编码:注册驱动 获取链接的部分写死 sql语句 ➡️ 配置文件
- 操作繁琐: 设置参数 封装结果集 ➡️ 自动完成
快速入门
Mybatis 官网
按步骤进行mybatis配置
<?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">
<mapper namespace="org.mybatis.example.BlogMapper">
<select id="selectBlog" resultType="Blog">
select * from Blog where id = #{id}
</select>
</mapper>
这是Mybatis的官方解释
注意命名空间和id
//加载mybatis核心配置文件,获取SqlSessionFactory
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 获取SqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
// 执行sql语句
List<Object> users = sqlSession.selectList("test.selectAll");
System.out.println(users);
// 资源关闭
sqlSession.close();
Mapper代理开发
将UserMapper 抽象成对象
直接使用对象中的函数来进行sql语言的执行
第一点十分小心,如果将SQL的映射文件放在resource下记得保持包的结构统一
包扫描的模式可以帮助在config文件内简化所有xml配置路径
public static void main(String[] args) throws IOException {
//加载mybatis核心配置文件,获取SqlSessionFactory
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 获取SqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
// 获取mybatis的Mapper代理对象
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> users = userMapper.selectAll();
System.out.println(users);
// 资源释放
sqlSession.close();
}
}
mybatis核心配置文件介绍
The MyBatis configuration contains settings and properties that have a dramatic effect on how MyBatis behaves. The high level structure of the document is as follows:
MyBatis可以配置多个环境。这有助于您出于任意原因将SQL Maps应用于多个数据库。例如,您可能对开发、测试和生产环境有不同的配置。或者,您可能有多个共享相同模式的生产数据库,并且您希望为两者使用相同的SQL映射。有很多用例。
不过,有一件重要的事情要记住:虽然您可以配置多个环境,但每个SqlSessionFactory实例只能选择一个。
<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://localhost:3306/mybatis?useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="qishimu621608"/>
</dataSource>
</environment>
</environments>
在对应的default可以切换对应的数据源信息
mybatis xml的配置标签一定要按照循序来书写
功能设计思路
是否需要参数
返回值类型的包装
sql语句的书写
编写,测试
统一数据库字段名 和 实体类属性名
- 对sql的查询语句起别名 用别名和实体类的属性名进行对应(每次查询都需要使用别名 不太方便)
- 定义sql片段 缺点定义死不灵活
- resultMap 将column 和 property对应,最常用将实体类的属性 进行映射(ID 唯一标识 type映射类型 result column映射字段)
参数的传入:
Preparing: select * from tb_brand where id = ?
Parameters: 1(Integer)
参数占位符:
- #{} 会将其替换为?. 为了防止sql注入
- ${} 拼sql,会出现sql注入的问题
- 可以通过pa rameterType设置参数类型(但其实在接口处有定义所以可以省略)
- 特殊字符的处理 比如<(会和<>冲突) 处理方式1. 转义字符 2.CDATA区
在参数传递的时候使用,一般都用#{}
对于多个参数的传入
- 用@Param注解
- 定义对应的实体类对象
- 对应对应的Map对象
主要都是保证SQL语句中的参数名和对应的参数名里的内容要保持一致
但是用户并不一定会填写所有数据 我们如何设置条件的动态查询
动态SQL
mybatis提供了许多标签去实现这个动态SQL的功能
- if: 条件判断 test:逻辑表达式 (xml里标签的如何连接多个if标签 and)
解决办法:1:前面加个1=1 恒等式过渡
2: where标签 - choose (when,otherwise)类似于java中的switch
注意书写时事务的开启与提交
生成放回主键
批量删除
foreach :
mybatis 会将数组参数,封装为一个Map集合
默认:array 为数组 k 如果不想使用array作为参数可以使用@Param作为注解去改变默认key的名称
collection 是遍历的集合
foreach标签的格式如下:
<foreach collection="" item="" index="" open="" separator="" close="">
</foreach>
collection:数组或可迭代对象
item:数组中的元素或本次迭代的元素
index:数组中的索引或本地迭代的序号
open:指定开头的字符串
close:指定结尾的字符串
separator:迭代之间的分隔符
注意:如果可迭代对象是Map对象(或者Map.Entry对象的集合)时,index是键,item是值
MyBatis参数封装
ParamNameResolver类来进行参数的封装
多个参数
多个参数传入时 mybatis会将多个参数封装为Map集合
对于Map的K V
User selectDemo(@Param("username")String username, @Param("password")String password);
value 是我们传入的各个参数值 比如username 和 password
在我们不进行设置的时候
mybatis会自动的将将K设置为arg0 arg1(param1或者 param2)
mybatis源码 对于 多参数的处理
public Object getNamedParams(Object[] args) {
int paramCount = this.names.size();
if (args != null && paramCount != 0) {
if (!this.hasParamAnnotation && paramCount == 1) {
Object value = args[(Integer)this.names.firstKey()];
return wrapToMapIfCollection(value, this.useActualParamName ? (String)this.names.get(this.names.firstKey()) : null);
} else {
// 对于多参数的处理部分
Map<String, Object> param = new MapperMethod.ParamMap();
int i = 0;
for(Iterator var5 = this.names.entrySet().iterator(); var5.hasNext(); ++i) {
Map.Entry<Integer, String> entry = (Map.Entry)var5.next();
param.put((String)entry.getValue(), args[(Integer)entry.getKey()]);
String genericParamName = "param" + (i + 1);
if (!this.names.containsValue(genericParamName)) {
param.put(genericParamName, args[(Integer)entry.getKey()]);
}
}
return param;
}
} else {
return null;
}
}
可以使用默认的@Param注解,替换Map集合中的默认的arg名称
建议使用@Param注解 增加代码的可读性
单个参数
public static Object wrapToMapIfCollection(Object object, String actualParamName) {
MapperMethod.ParamMap map;
if (object instanceof Collection) {
map = new MapperMethod.ParamMap();
map.put("collection", object);
if (object instanceof List) {
map.put("list", object);
}
Optional.ofNullable(actualParamName).ifPresent((name) -> {
map.put(name, object);
});
return map;
} else if (object != null && object.getClass().isArray()) {
map = new MapperMethod.ParamMap();
map.put("array", object);
Optional.ofNullable(actualParamName).ifPresent((name) -> {
map.put(name, object);
});
return map;
} else {
return object;
}
}
}
- POJO类型 属性名和参数占位符名称一致
- Map类 K 和 参数占位符名称保持一致
- Collection 转化为Map() K:arg0 和 collection
- list 再加一个list
- array arg0 和 array
多是封装成arg0
在封装成数组的时候都适用@Param进行注解