持久层框架MyBatis
1. mybatis介绍
-
传统框架的缺点:
使用jdbc需要程序员创建连接,手写sql,处理结果集,使用了mybatis框架后,创建连接,结果集处理都由框架来完成。 -
mybatis它是轻量级持久层框架,由ibatis演化而来。它自动连接数据库,将数据库的结果集封装到对象中POJO。
2. 执行流程
Mybatis启动时:
- 读取application.yml中的数据库名称,username,password
- 读取所有xml
- @mapperScan(“mapper”) ,为每个接口创建一个代理对象,放到spring容器中。
执行的流程:
- Controller中通过autowired从spring容器中取到代理对象
- catagoryMapper.selectByExample(),执行mybatis中的invoke(),连接数据库
- 得到方法名selectByExample,得到接口名,包名,namespace=包名+接口名,根据namespace找到xml文件
- 根据方法名找到sql语句
- 执行sql,得到resultSet
- 遍历,得到每一行数据,class.forname(实体类名),clazz.newInstance()(创建对象),把对象放到list中 return list
3. 使用步骤
- 使用逆向工程generater项目生成xml,接口,pojo,example
- 创建springboot项目,依赖web,mybatis,mysql driver
- 配置application.yml,配置数据库信息,xml的位置,日志log
- Application添加 @MapperScan(“mapper包名”),mybatis框架会为包下的每个接口创建代理对象。
- Controller通过@Autowried从spring容器中取到代理对象
- 代理对象有insert(),delete(),update(),查询用example,criteria(为每个列生成)
代码实现举例:商品分类CRUD操作
- 由逆向工程generater项目生成mapper.xml,接口,pojo,example
- 配置application.yml
server:
port: 8080
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/mall?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2b8
username: root
password: 123456
mybatis:
mapperLocations: classpath:com.tedu.mybatis01_crud.mapper/*.xml
logging:
path: ./logs
level:
com.tedu.mybatis01_crud.mapper: debug
- Mybatis01CrudApplication.java
添加@MapperScan注解
package com.tedu.mybatis01_crud;
@SpringBootApplication
//@MapperScan:mybatis框架会自动为mapper包下的接口创建动态代理对象
//动态代理对象会自动连接数据库,找到sql,执行,把resultSet转成实体类
@MapperScan("com.tedu.mybatis01_crud.mapper")
public class Mybatis01CrudApplication {
public static void main(String[] args) {
SpringApplication.run(Mybatis01CrudApplication.class, args);
}
}
- controller层
package com.tedu.mybatis01_crud.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.tedu.mybatis01_crud.mapper.CategoryMapper;
import com.tedu.mybatis01_crud.pojo.Category;
import com.tedu.mybatis01_crud.pojo.CategoryExample;
@RestController
@RequestMapping("/category")
public class CategoryController {
//接口没有实现类,mybatis框架会自动为mapper包下的所有接口创建代理类
//创建一个代理对象,把代理对象放到容器中
//从容器中取代理对象
@Autowired
CategoryMapper categoryMapper;
//添加
@RequestMapping("/insert")
@CrossOrigin
public String insert(Category category) {
return "添加的行="+categoryMapper.insert(category);
}
//修改
@RequestMapping("/update")
@CrossOrigin
public String update(Category category) {
//:8080/update?catagoryId=1&categoryName=笔记本
//:8080/selectDesc
//updateByPrimaryKey()
//updateByPrimaryKeySelective 属性为空,不生成desc=null
return "更新的行:"+categoryMapper.updateByPrimaryKeySelective(category);
}
//删除
@RequestMapping("/delete")
@CrossOrigin
public String delete(Integer categoryId) {
return "删除的行:"+categoryMapper.deleteByPrimaryKey(categoryId);
}
//升序
@RequestMapping("/selectAsc")
@CrossOrigin
public List<Category> selectAsc(){
CategoryExample example = new CategoryExample();
example.setOrderByClause("category_id asc");
return categoryMapper.selectByExample(example);
}
//降序
@RequestMapping("selectDesc")
@CrossOrigin
public List<Category> selectDesc(){
CategoryExample example = new CategoryExample();
example.setOrderByClause("category_id desc");
return categoryMapper.selectByExample(example);
}
//自动生成where
@RequestMapping("/selectByName")
@CrossOrigin
public List<Category> selectByName(String categoryName){
CategoryExample example = new CategoryExample();
example.setOrderByClause("category_id desc");
//Criteria是CategoryExample中的内部类
//产生where语句
CategoryExample.Criteria criteria = example.or();
criteria.andCategoryNameEqualTo(categoryName);
return categoryMapper.selectByExample(example);
}
@RequestMapping("/selectAll")
@CrossOrigin
public List<Category> selectAll(){
System.out.println(categoryMapper);
return categoryMapper.selectByExample(null);
}
}
4. 关联关系
Mybatis表现关联关系只有两种association(一对一)、collection(一对多),表现很简洁。
4.1 一对一
-
分析
-
代码实现
4.2 一对多
-
分析
-
代码实现
5. 参数占位符
mybatis本质就是拼接SQL语句。
- #{name}
防止SQL注入;如果参数是一个字符串类型。chen 拼接SQL语句时会根据类型,自动加相关符号。例如字符串类型’chen’。 - ${orderby}
${} 原样输出,很危险,有SQL注入风险。
6. 复杂搜索
6.1 动态SQL语句
举例:
<mapper namespace="com.tedu.mybaits02_multiTableQuery.mapper.ItemMapper">
<!-- resultType=集合中数据的类型 -->
<select id="selectByCategoryIdAndName" parameterType="com.tedu.mybaits02_multiTableQuery.pojo.Item"
resultType="com.tedu.mybaits02_multiTableQuery.pojo.Item">
SELECT item_id as itemId,item_name as itemName,category_id as categoryId
from item
<where>
<if test="categoryId != null">
category_id=#{categoryId}
</if>
<if test="itemName != null">
AND item_name LIKE concat('%',#{itemName},'%')
</if>
</where>
</select>
</mapper>
6.2 集合参数
foreach的主要用在构建sql中的in条件中,它可以在SQL语句中进行迭代一个集合。
属性:
- collection:表示传入的参数。该属性是必须指定
主要有以下3种情况:- 如果传入的是单参数且参数类型是一个List的时候,collection属性值为list
- 如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array
- 如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了,当然单参数也可
- item:表示集合中每一个元素进行迭代时的别名。
- open:表示该语句以什么开始
- close:表示该语句以什么结束
- separator:表示在每次进行迭代之间以什么符号作为分隔
<mapper namespace="com.tedu.mybaits02_multiTableQuery.mapper.ItemMapper">
<select id="selectByList" parameterType="Integer" resultType="com.tedu.mybaits02_multiTableQuery.pojo.Item">
SELECT item_id as itemId,
item_name as itemName,
category_id as categoryId
from item
<where>
<!-- itemId in (2,3) -->
item_id in
<foreach collection="list" item="itemId" open="(" separator="," close=")">
#{itemId}
</foreach>
</where>
</select>
</mapper>