栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot整合mybatis

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot整合mybatis

1、mybatis是什么

MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。

2.整合

两种方式:

  • 新建一个mybaits-config.xml文件,内容配置其中
  • 在springboot核心配置文件application.yaml中,配置mybatis内容(这边只展示第二种)

2.0 前期工作:保证可以连接上数据库
导入依赖:

	
   
       org.springframework.boot
       spring-boot-starter-jdbc
   
   
   
       mysql
       mysql-connector-java
   
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: xxx
    url: jdbc:mysql://localhost:3306/mybatis

springboot中默认使用hikari连接池,号称最快的连接池。连接池还有DBCP,c3p0,druid…

2.1 导入依赖


  
      org.mybatis.spring.boot
      mybatis-spring-boot-starter
      2.2.0
  

2.2 创建包和类

mapper层:

@Mapper
public interface EmployeeMapper {
    public Employee getEmpById(Integer id);
}

mapper层对应的xm文件:




    
        select * from employee where id = #{id}
    

2.3 在application.yaml配置mybatis

mybatis:   
  mapper-locations: classpath:mybatis/mapper/*.xml   # 找到mapper层对应的xml文件
  config-location: mybatis-config.xml   # mybatis配置文件,resource目录下

mybaits的属性设置参考文档:https://mybatis.net.cn/configuration.html#settings

3. 使用注解版mybaits

在mapper接口的方法上,使用注解增删改查@Update()、 @Insert()、 @Select()、@Delete()

@Insert("insert into employee (name,age,position) values(#{name},{age},#{position})")
void insert(Employee employee);

@Select("select * from employee where id = #{id}")
void selectById(Integerid);
4.实战过程
  1. 引入mybatis-spring-boot-start
  2. 配置application.yaml中,指定mapper-locations位置
  3. 编写mapper接口并标注@Mapper注解
  4. 简单方法直接使用注解
  5. 复杂方法编写在mapper.xml进行绑定映射
  6. @MapperScan(“com.lmh.mapper”)简化,该目录下的mapper接口就可不添加@Mapper注解
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/914890.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号