首页 > 编程语言 > 详细

Spring Boot 学习(一) mybatis整合

时间:2021-07-02 00:51:38      阅读:16      评论:0      收藏:0      [点我收藏+]

1.配置模式

  • 全局配置文件
  • SqlsessionFactory:已经自动配置完成
  • SqlSession: 已经自动配置SqlSessionTemplate,组合了SqlSession,真正对数据库的CRUD用的就是sqlsession
  • Mapper:  只要我们写的操作Mybatis的接口标注了@Mapper就会被自动扫描进来

引入mybatis   的 pom.xml  ,mybatis的官方starters的地址

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

观察MybatisAutoConfiguration里面有一个绑定类

@EnableConfigurationProperties({MybatisProperties.class})  //mybatis配置项绑定类
@AutoConfigureAfter({DataSourceAutoConfiguration.class, MybatisLanguageDriverAutoConfiguration.class})

其中MybatisProperties里面有绑定的是:@ConfigurationProperties(prefix = "mybatis")
而MybatisAutoConfiguration里面有定义的容器为SqlSessionFactory已经配置完成
技术分享图片
@Bean
    @ConditionalOnMissingBean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
        SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
        factory.setDataSource(dataSource);
        factory.setVfs(SpringBootVFS.class);
        if (StringUtils.hasText(this.properties.getConfigLocation())) {
            factory.setConfigLocation(this.resourceLoader.getResource(this.properties.getConfigLocation()));
        }

        this.applyConfiguration(factory);
        if (this.properties.getConfigurationProperties() != null) {
            factory.setConfigurationProperties(this.properties.getConfigurationProperties());
        }

        if (!ObjectUtils.isEmpty(this.interceptors)) {
            factory.setPlugins(this.interceptors);
        }

        if (this.databaseIdProvider != null) {
            factory.setDatabaseIdProvider(this.databaseIdProvider);
        }

        if (StringUtils.hasLength(this.properties.getTypeAliasesPackage())) {
            factory.setTypeAliasesPackage(this.properties.getTypeAliasesPackage());
        }

        if (this.properties.getTypeAliasesSuperType() != null) {
            factory.setTypeAliasesSuperType(this.properties.getTypeAliasesSuperType());
        }

        if (StringUtils.hasLength(this.properties.getTypeHandlersPackage())) {
            factory.setTypeHandlersPackage(this.properties.getTypeHandlersPackage());
        }

        if (!ObjectUtils.isEmpty(this.typeHandlers)) {
            factory.setTypeHandlers(this.typeHandlers);
        }

        if (!ObjectUtils.isEmpty(this.properties.resolveMapperLocations())) {
            factory.setMapperLocations(this.properties.resolveMapperLocations());
        }

        Set<String> factoryPropertyNames = (Set)Stream.of((new BeanWrapperImpl(SqlSessionFactoryBean.class)).getPropertyDescriptors()).map(FeatureDescriptor::getName).collect(Collectors.toSet());
        Class<? extends LanguageDriver> defaultLanguageDriver = this.properties.getDefaultScriptingLanguageDriver();
        if (factoryPropertyNames.contains("scriptingLanguageDrivers") && !ObjectUtils.isEmpty(this.languageDrivers)) {
            factory.setScriptingLanguageDrivers(this.languageDrivers);
            if (defaultLanguageDriver == null && this.languageDrivers.length == 1) {
                defaultLanguageDriver = this.languageDrivers[0].getClass();
            }
        }

        if (factoryPropertyNames.contains("defaultScriptingLanguageDriver")) {
            factory.setDefaultScriptingLanguageDriver(defaultLanguageDriver);
        }

        return factory.getObject();
    }
View Code

其中也配置了SqlSession

 @Bean
    @ConditionalOnMissingBean
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
        ExecutorType executorType = this.properties.getExecutorType();
        return executorType != null ? new SqlSessionTemplate(sqlSessionFactory, executorType) : new SqlSessionTemplate(sqlSessionFactory);
    }

 

2.操作Mybatis

  1.首先得有一个mybatis的全局配置文件,可在yaml中进行配置

根据官方文档的全局配置文件

技术分享图片
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
  <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC"/>
      <dataSource type="POOLED">
        <property name="driver" value="${driver}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
      </dataSource>
    </environment>
  </environments>
  <mappers>
    <mapper resource="org/mybatis/example/BlogMapper.xml"/>
  </mappers>
</configuration>
View Code

因为springboot全部配置好了所以只需要

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

</configuration>

  2.Mapper映射文件

<?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.sp.mapper.WholeMessage">
<!--    public Whole getWhole(Integer id);-->
    <select id="getWhole" resultType="com.sp.bean.Whole">
        select * from whole where id = #{id}
    </select>
</mapper>

  3.对配置文件yaml进行配置

  • 先指定mybatis全局配置的位置:
  • 再指定所有sql映射文件:
mybatis:
  config-location: classpath:mybatis/mybatis-config.xml  #mybatis文件夹下的xml全局配置文件
  mapper-locations: classpth:mybatis/mapper/*.xml   #mybatis文件夹下的mapper下的所有xml文件

配置mapper接口

package com.sp.mapper;

import com.sp.bean.Whole;

public interface WholeMapper {
    public Whole getWhole(Integer id);
}

配置service类

package com.sp.service;

import com.sp.bean.Whole;
import com.sp.mapper.WholeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class WholeService {

    @Autowired
    WholeMapper wholeMapper;

    public Whole wholegetid(Integer id) {
        return wholeMapper.getWhole(id);
    }

}

 

配置Controller类

 @Autowired
    WholeService wholeService;
    @ResponseBody
    @GetMapping("/sqltest")

    public Whole getByid(@RequestParam("id") Integer id) {
        return wholeService.wholegetid(id);
    }

 

基于注解的方式

在mapper接口里的类中添加注解@select(“sql语句”),其中的mybatis-config.xml以及mybaits文件下的mapper.xml文件也可以不用配置了

package com.sp.mapper;

import com.sp.bean.Whole;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

@Mapper
public interface WholeMapper {
    @Select("select * from whole where GOODS_ID = #{id}")
    public Whole getWhole(Integer id);

}

 

 

注解模式和基本配置模式可以混搭使用

 

用注解的方式如果想要加上原配置版本的其他方法功能时可以再添加一个注解@Options

@Mapper
public interface WholeMapper {
    @Select("select * from whole where GOODS_ID = #{id}")
    @Options(useGeneratedKeys = true,keyProperty = "GOODS_ID")    //获取自增,字段名为GOODS_ID
    public Whole getWhole(Integer id);

}

最佳实战

  1. 引入mybatis-starter
  2. 配置application.yaml中,指定mapper-loaction位置即可
  3. 编写Mapper接口并标注@Mapper注解
  4. 简单方法总结注解方式
  5. 复杂方法编写mapper.xml进行绑定映射

 

Spring Boot 学习(一) mybatis整合

原文:https://www.cnblogs.com/YuyuFishSmile/p/14960784.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!