三大框架 —— 持久层框架MyBatis

本文详细介绍了MyBatis框架,包括其介绍、执行流程、使用步骤和关键特性,如参数占位符、关联关系处理及复杂搜索。通过具体代码示例展示了商品分类的CRUD操作,帮助读者掌握MyBatis的实战应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. mybatis介绍

  • 传统框架的缺点:
    使用jdbc需要程序员创建连接,手写sql,处理结果集,使用了mybatis框架后,创建连接,结果集处理都由框架来完成。

  • mybatis它是轻量级持久层框架,由ibatis演化而来。它自动连接数据库,将数据库的结果集封装到对象中POJO。

2. 执行流程

Mybatis启动时:

  1. 读取application.yml中的数据库名称,username,password
  2. 读取所有xml
  3. @mapperScan(“mapper”) ,为每个接口创建一个代理对象,放到spring容器中。

执行的流程:

  1. Controller中通过autowired从spring容器中取到代理对象
  2. catagoryMapper.selectByExample(),执行mybatis中的invoke(),连接数据库
  3. 得到方法名selectByExample,得到接口名,包名,namespace=包名+接口名,根据namespace找到xml文件
  4. 根据方法名找到sql语句
  5. 执行sql,得到resultSet
  6. 遍历,得到每一行数据,class.forname(实体类名),clazz.newInstance()(创建对象),把对象放到list中 return list

3. 使用步骤

  1. 使用逆向工程generater项目生成xml,接口,pojo,example
  2. 创建springboot项目,依赖web,mybatis,mysql driver
  3. 配置application.yml,配置数据库信息,xml的位置,日志log
  4. Application添加 @MapperScan(“mapper包名”),mybatis框架会为包下的每个接口创建代理对象。
  5. Controller通过@Autowried从spring容器中取到代理对象
  6. 代理对象有insert(),delete(),update(),查询用example,criteria(为每个列生成)

代码实现举例:商品分类CRUD操作

  1. 由逆向工程generater项目生成mapper.xml,接口,pojo,example
  2. 配置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
  1. 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);
	}
}
  1. 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种情况:
    1. 如果传入的是单参数且参数类型是一个List的时候,collection属性值为list
    2. 如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array
    3. 如果传入的参数是多个的时候,我们就需要把它们封装成一个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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值