java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot整合Mybatis

SpringBoot开发之整合Mybatis详解

作者:韩_师兄

这篇文章主要介绍了SpringBoot开发之整合Mybatis详解,MyBatis是一个半自动的ORM框架,它允许我们通过编写SQL语句来操作数据库,使用MyBatis,我们可以通过定义映射文件(XML文件)或使用注解的方式将Java对象与数据库表进行映射,需要的朋友可以参考下

1 整合Mybatis

Spring Boot官方的依赖包:

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>

1 配置模式

//  MyBatis配置项绑定类。
@EnableConfigurationProperties(MybatisProperties.class)
@AutoConfigureAfter({ DataSourceAutoConfiguration.class, MybatisLanguageDriverAutoConfiguration.class })
public class MybatisAutoConfiguration{}
@ConfigurationProperties(prefix = "mybatis")
public class MybatisProperties

配置修改mybatis:

# 配置mybatis规则
mybatis:
  config-location: classpath:mybatis/mybatis-config.xml  # 全局配置文件位置
  mapper-locations: classpath:mybatis/mapper/*.xml  # sql映射文件位置
# Mapper接口--->绑定Xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.cf.admin.mapper.AccountMapper">
<!--    public Account getAcct(Long id); -->
    <select id="getAcct" resultType="com.cf.admin.bean.Account">
        select * from  t_user where  id=#{id}
    </select>
</mapper>

配置 private Configuration configuration; mybatis.configuration下面的所有,就是相当于改mybatis全局配置文件中的值

# 配置mybatis规则
mybatis:
#  config-location: classpath:mybatis/mybatis-config.xml
  mapper-locations: classpath:mybatis/mapper/*.xml
  configuration:
    map-underscore-to-camel-case: true
# 可以不写全局;配置文件,所有全局配置文件的配置都放在configuration配置项中即可

使用流程:

2 注解模式

@Mapper
public interface CityMapper {
    @Select("select * from t_user where id=#{id}")
    public User getById(Long id);
}

3 混合模式

@Mapper
public interface CityMapper {
    @Select("select * from t_user where id=#{id}")
    public User getById(Long id);
}

使用流程:

2 整合MyBatis-Plus

 概述

MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

推荐安装 MybatisX 插件

使用

引入依赖

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.1</version>
        </dependency>

说明:

优点:

让Mapper继承 BaseMapper 就可以拥有简单crud的能力

到此这篇关于SpringBoot开发之整合Mybatis详解的文章就介绍到这了,更多相关SpringBoot整合Mybatis内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文