博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
springboot --Mybatis注解版和配置文件版
阅读量:3921 次
发布时间:2019-05-23

本文共 5461 字,大约阅读时间需要 18 分钟。

序言:

简单查询可以用JPA, 但复杂查询要用Mybatis,因为Mybatis的SQL语句相对于JPA灵活(有逻辑判断,对返回数据的多样性处理灵活等等)

1、相关依赖

org.springframework.boot
spring-boot-starter-jdbc
org.mybatis.spring.boot
mybatis-spring-boot-starter
2.1.1
mysql
mysql-connector-java
8.0.11

2、数据库连接(application.yml)

spring:  datasource:    username: root    password: admin    url: jdbc:mysql://localhost:3306/abc?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false    driver-class-name: com.mysql.cj.jdbc.Driver

一、使用注解版Mybatis(很简单):

1、在主程序上添加注解让spring扫描这个包下所有mapper接口类

@MapperScan(value=“com.example.mapper”)

package com.example;import org.mybatis.spring.annotation.MapperScan;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@MapperScan(value = "com.example.demo.dao")@SpringBootApplicationpublic class MybatisApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisApplication.class, args); }}

2、创建一个Mapper接口类

package com.example.mapper;import org.apache.ibatis.annotations.Delete;import org.apache.ibatis.annotations.Insert;import org.apache.ibatis.annotations.Options;import org.apache.ibatis.annotations.Select;import org.apache.ibatis.annotations.Update;import com.example.bean.Department;public interface DepartmentMapper {
@Select("select * from department where id=#{id}") public Department get(Integer id); @Delete("delete from department where id=#{id}") public Integer delete(Integer id); @Options(useGeneratedKeys = true,keyProperty = "id") @Insert("insert into department(departmentName) values(#{departmentName})") public Integer insert(Department department); @Update("update department set departmentName=#{departmentName} where id=#{id}") public Integer update(Department department);}

3、调用并使用

@Autowired	DepartmentMapper mapper;		@ResponseBody	@GetMapping("/get/{id}")	public Department BB(@PathVariable("id")int id) {
return mapper.get(id); }

二、使用配置文件

1、在主程序上添加注解让spring扫描这个包下所有mapper接口类

@MapperScan(value=“com.example.mapper”)

2、创建一个Mapper接口类(接口类和Mapper.xml的文件名必须相同,否则Mapper.xml无法找到接口类的方法,原因不详

package com.example.demo.dao;import com.example.demo.bean.User;import org.apache.ibatis.annotations.Mapper;import java.util.List;/** * @author Huangyt * @version 1.0 * @date 2020/5/12 20:15 */public interface UserMapper {
List
findAll();}

3、在resources文件夹下并且与Mapper接口同包名下创建×××Mapper.xml配置文件(或者在配置文件中指定mapper.xml的位置)(接口类和Mapper.xml的文件名必须相同,否则Mapper.xml无法找到接口类的方法,原因不详

关于Mybatis配置文件默认的存放位置

1、mybatis的配置文件放在resource文件夹下

2、×××Mapper.xml文件放在resource文件夹下的和Mapper接口类同一个包下

3、也可以通过配置文件修改配置文件的存放路径:

mybatis:  config-location: classpath:mybatis/mybatis-config.xml  mapper-locations: classpath:mybatis/mapper/*.xml

mybatis-config.xml(不用配置数据源和Mappers标签 == 毫无作用 == 可以不用添加)

mybatis-config.xml不用配置数据源的原因:

要注意我们配置pom.xml的Mybatis依赖是sprringboot的,所以当启动springboot时会自动扫描

application.properties配置文件,并不会扫描mybatis-config.xmll配置文件中的数据源。所以你此时必须将

连接数据库的参数写在application.properties配置文件中。

//连接数据库相关操作之前已经在approperties.yml已经配置好, 以下连接数据库的操作可以省略
//扫描mapper的操作之前在主程序已经添加了MapperScan, 所以也可以省略

4、调用并使用

注意:此时会出现userMapper会爆红:无法注入的异常,但运行正常的现象,原因不详。有人说是

idea的问题还可以忽略,如果要解决可以以下方法解决

1、通过将@Autowired 改成@Resource即可

2、Mapper接口类上添加@Repository

package com.example.demo;import com.example.demo.bean.User;import com.example.demo.dao.UserMapper;import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import javax.annotation.Resource;import java.io.Serializable;import java.util.List;@SpringBootTestclass DemoApplicationTests {
@Autowired UserMapper userMapper; @Test void contextLoads() {
List
all = userMapper.findAll(); for(User user : all){
System.out.println(user); } }}

当然注解和配置文件两种方式可以一起配合使用


关于Mybatis的Mapper文件和*xml文件的位置
1、在resources文件夹下创建和src相同的文件夹结构,Mapper文件和*.xml文件等同于一个文件夹下,固然生效
在这里插入图片描述

关于Mybatis复杂查询例子

select标签:

id:对应mapper的方法名

parameterType:参数类型

resultMap:自定义查询结果的返回格式(因为复杂查询得到的数据形式是多变的,用resultMap自定义映射关系,手动映射,指定表的哪一列数据对应实体类的哪个属性)

和resultType的区别是:自动将表和类的属性映射,但字段名必须相同;因为resultMap已经设置表和类属性的映射关系,所以字段名不相同也没关系。

(Mybatis查询得到的结果都是map类型)

if标签

test:条件

_parameter:指传入的参数

resultMap标签

id:自定义resultMap的唯一id

type:将查询到的结果返回的实体类(类路径要写全)

id(主键)标签、result(属性)标签

column:表属性的字段名

property:实体类属性的字段名

collection标签(表示一个集合属性List—一对多的关系)

property:这个List集合对应实体类的属性

ofType:List集合中的类型

转载地址:http://wyern.baihongyu.com/

你可能感兴趣的文章
在 Blazor WebAssembly 中使用 gRPC-Web
查看>>
【实战 Ids4】║ 在Swagger中调试认证授权中心
查看>>
.NET Core开发实战(第10课:环境变量配置提供程序)--学习笔记
查看>>
WTM系列视频教程:View和Taghelper
查看>>
面试官:你连HTTP请求Post和Get都不了解?
查看>>
.NET Core 3.0 即将结束生命周期,建议迁移 3.1
查看>>
开源、免费、企业级的SiteServer CMS .NET CORE 7.0 预览版发布
查看>>
基于.NET下的人工智能|利用ICSharpCore搭建基于.NET Core的机器学习和深度学习的本地开发环境...
查看>>
【朝夕Net社区技术专刊】Core3.1 WebApi集群实战专题---WebApi环境搭建运行发布部署篇...
查看>>
200行代码,7个对象——让你了解ASP.NET Core框架的本质[3.x版]
查看>>
.NET Core开发实战(第21课:中间件:掌控请求处理过程的关键)--学习笔记(下)...
查看>>
对比Java和.NET多线程编程
查看>>
[头脑风暴] 解读Docker Bridge网络模型
查看>>
集成平台集群任务动态分派
查看>>
【.net core】电商平台升级之微服务架构应用实战
查看>>
【翻译】.NET 5 Preview 1 发布
查看>>
使用GUI工具Portainer.io管控Docker容器
查看>>
Abp vNext发布v2.3!
查看>>
.NET Core开发实战(第27课:定义Entity:区分领域模型的内在逻辑和外在行为)--学习笔记...
查看>>
BeetleX之vue-autoui自匹配UI插件
查看>>