注册 X
我已阅读并同意  服务条款
首页 > IT技术笔记 > 查看笔记

springboot集成mybatis,springboot使用mybatis

pom文件增加依赖

<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.0.0</version>

</dependency>

        <!--数据库连接池-->

        <dependency>

            <groupId>com.zaxxer</groupId>

            <artifactId>HikariCP</artifactId>

        </dependency>

1、首先在application.yml文件加入数据源连接信息以及mybatis的别名扫描包和mapper.xml映射文件路径。

2019-07-27_2252541.jpg

2、在resource新建mappers文件夹

3、新建com.datasource包,加入JdbcProperties类和JdbcConfig类

4、启动类加入@MapperScan("com.rshare.mapper") 扫描mapper接口

2019-07-27_230047.jpg


mapper接口

2019-07-27_230524.jpg


对应的xml文件:

2019-07-27_230648.jpg

点击复制

package com.datasource;

import org.springframework.boot.context.properties.ConfigurationProperties;

/**
 * @author 这是一个jdbc配置类
 * prefix yml 里面的前缀 他会自动寻找位置并且赋值
 */
@ConfigurationProperties(prefix = "jdbc") 
public class JdbcProperties {
     private  String url;
     private String driverClassName;
     private String username;
     private String password;
 
     public String getUrl() {
          return url;
     }
 
     public void setUrl(String url) {
          this.url = url;
     }
 
     public String getDriverClassName() {
          return driverClassName;
     }
 
     public void setDriverClassName(String driverClassName) {
          this.driverClassName = driverClassName;
     }
 
     public String getUsername() {
          return username;
     }
 
     public void setUsername(String username) {
          this.username = username;
     }
 
     public String getPassword() {
          return password;
     }
 
     public void setPassword(String password) {
          this.password = password;
     }
}

package com.datasource;

import com.zaxxer.hikari.HikariDataSource;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
 
/**
 * @author 数据源配置类
 */
@Configuration
@EnableConfigurationProperties(JdbcProperties.class)
public class JdbcConfig {
 
     @Bean
     public DataSource getDataSource(JdbcProperties jdbc){
          HikariDataSource dataSource = new HikariDataSource();
          dataSource.setJdbcUrl(jdbc.getUrl());
          dataSource.setDriverClassName(jdbc.getDriverClassName());
          dataSource.setUsername(jdbc.getUsername());
          dataSource.setPassword(jdbc.getPassword());
          return dataSource;
     }
}
			
		

 打赏        分享



评论