SpringBoot 2.X integration Mybatis

1. Create a project environment

Check the Web, Mybatis, MySQL, as
Here Insert Picture Description
dependent as follows

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>

Note Once created, named MyBatis dependent naming and other libraries are not the same, this integration is not springboot own jar package, which means that the starter is provided by a third party, like a Druiddata source, just as the third party of.

Easy to read, the first location information, the following posted write operations, as shown below:
Here Insert Picture Description

2, the configuration database connection information

As used herein yml way

spring:
  datasource:
    username: root
    url: jdbc:mysql://localhost:3306/ufida?serverTimezone=UTC
    password: 123456
    driver-class-name: com.mysql.jdbc.Driver
#如果要使用Druid数据源就要导入相应jar包,当然也可以不指定type
    type: com.alibaba.druid.pool.DruidDataSource

After configuration, MyBatis can create entity classes to use.

3, the preparation of an entity class

Userdao under dao package: Entity Class

public class Userdao {
    private int user_id;
    private String userName;
    private String passWord;
    private int usertypeid;

    getXXX...
    setXXX...
    toString...
}

4, write Mapper interface class

Mapper interface class: UserMapper under mapper package

@Mapper
@Repository   
public interface UserMapper {
   //只是整合测试,为了可读性,只写了一个方法
    List<Userdao> queryUserList();
}

Here we must note @Mapper annotation, @ Mapper add annotations in position above the interface class and its role is after compilation will generate a corresponding interface class, this method is also the official recommended! Here are just a written test integrated mybatis Mapper interface can be, if there is a demand for a lot of the interface implementation class have become, you need to add @Mapper comment on each interface class, too much trouble, to solve this problem with @MapperScan comment. Simply put @MapperScan annotation is equivalent to directly scan the specified package, the code above where the package is com.yichunnnn.jdbcboot.mapperunder the package, if you use @MapperScan notes, is equivalent to the following

@MapperScan("com.yichunnnn.jdbcboot.mapper")  //相当于@Mapper
@SpringBootApplication
public class JdbcbootApplication {
    public static void main(String[] args) {
        SpringApplication.run(JdbcbootApplication.class, args);
    }
}

5, write Mapper mapping file

Mapper location map and write files named:classpath:mybatis/mapper/UserMapper.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.yichunnnn.jdbcboot.mapper.UserMapper">

    <select id="queryUserList" resultType="Userdao">
        select * from user
    </select>
</mapper>

Taking into account the readability, only here to write a query method, with particular attention to
Here Insert Picture Description
just being given the wrong one will!

6, SpringBoot integration Mybatis

In fact Mybatis integration process like most of our programmers life.

Before SpringBoot integration Mybatis, we recall memories before MyBatis when used alone, myBatis core configuration file to configure the data source, transaction, database connection account, password .... is full of goods that a person dry, everything myself. This is our trough

myBatis 与 spring 整合的时候,配置数据源、事务、连接数据库的账号什么的都交由 spring 管理就行,就不用什么都自己管理自己去干。这就是我们春风得意的时候,事业有着落...

再后来,SpringBoot 整合Mybatis的时候,数据源什么的,springboot都默认准备好了,甚至不使用mybatis配置文件也没问题,如果我们自己已经编写了 myBatis 的映射配置文件,则只要告诉 spring boot 这些文件的位置的好了,如下(yml写法),这简直是事业有成,迎娶白富美,走上人生巅峰...

#整合Mybatis   #指定myBatis的核心配置文件与Mapper映射文件
mybatis:
  mapper-locations: classpath:mybatis/mapper/*.xml
#注意:对应实体类的路径
  type-aliases-package: com.yichunnnn.jdbcboot.dao

Here Insert Picture Description
故事是美好的,然而事实却是骨感的.....

最后的配置文件也就如上图效果所示,如果需要完全理解配置文件可以从 org.mybatis.spring.boot.autoconfigure.MybatisProperties 类中查看(鼠标点击属性就可以进入),当然也可以从官方文档中查阅:http://mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/

7、编写controller层代码

@RestController
public class MybatisController {
    @Autowired
    private UserMapper userMapper;

    @GetMapping("/selectUser")
    public String selectUser(){
        List<Userdao> userdaos = userMapper.queryUserList();
        for (Userdao user : userdaos) {
            System.out.println(user);
        }
        return "select success == SpringBoot 2.X整合Mybatis成功!";
    }
}

运行测试
Here Insert Picture Description
效果如上,则整合成功!

8、SpringBoot 2.X整合Mybatis原理

SpringBoot 2.X整合Mybatis原理实际上就隐含在org.mybatis.spring.boot.autoconfigure 包中,这里面蕴含着SpringBoot 整合Mybatis的精华原理所在,具体位置如下
Here Insert Picture Description
在myBatis 与 spring 整合的时候,开发者需要自己提供两个Bean,一个SqlSessionFactoryBean,还有一个是MapperScannerConfigurer,在Spring Boot中,这两个东西虽然不用开发者自己提供了,但是并不意味着这两个Bean不需要了,在org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration类中,我们可以看到Spring Boot提供了这两个Bean,关键源码如下:

@org.springframework.context.annotation.Configuration
@ConditionalOnClass({ SqlSessionFactory.class, SqlSessionFactoryBean.class })
@ConditionalOnSingleCandidate(DataSource.class)
@EnableConfigurationProperties(MybatisProperties.class)
@AutoConfigureAfter(DataSourceAutoConfiguration.class)
public class MybatisAutoConfiguration implements InitializingBean {

  @Bean
  @ConditionalOnMissingBean
  public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
    SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
    factory.setDataSource(dataSource);
    return factory.getObject();
  }
  @Bean
  @ConditionalOnMissingBean
  public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
    ExecutorType executorType = this.properties.getExecutorType();
    if (executorType != null) {
      return new SqlSessionTemplate(sqlSessionFactory, executorType);
    } else {
      return new SqlSessionTemplate(sqlSessionFactory);
    }
  }
  @org.springframework.context.annotation.Configuration
  @Import({ AutoConfiguredMapperScannerRegistrar.class })
  @ConditionalOnMissingBean(MapperFactoryBean.class)
  public static class MapperScannerRegistrarNotFoundConfiguration implements InitializingBean {

    @Override
    public void afterPropertiesSet() {
      logger.debug("No {} found.", MapperFactoryBean.class.getName());
    }
  }
}

As can be seen from the annotation on the class, the current class when a path exists SqlSessionFactory, SqlSessionFactoryBeanand DataSourcewhen, where the configuration will be effective, SqlSessionFactoryand SqlTemplateare provided. Meaning of this code is that Spring Bootin MyBatisdoing an important reference when configuring multiple data sources!

Of course, if interest configuration properties for mybatis can also reference MybatisPropertiesclass, mainly in principle to explore more org.mybatis.spring.boot.autoconfigurepackage for the center reference!

If this article there is a little bit of help to you, then please point a chant praise, thank you ~

Finally, if there is insufficient or is not correct, please correct me criticism, grateful! If you have questions please leave a message, the absolute first time to reply!

I welcome you to focus on the public number, there are some java learning materials and a large wave of java e-books, such as Zhou Zhiming teacher depth java virtual machine, java programming ideas, the core technology volume, Westward design patterns, java concurrent programming combat ... .. is a java Bible, do not say fast car on Tomcat, ye who go! The main thing is to explore technology, yearning technology, the pursuit of technology, said good pots Friends is coming Oh ...

Here Insert Picture Description
Reference:
http://mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/

https://blog.csdn.net/u012702547/article/details/88643598

Guess you like

Origin www.cnblogs.com/yichunguo/p/12164679.html
Recommended