spring boot整合mybatis

工程层级结构

maven依赖



    4.0.0

    com.example
    save-search-service
    1.0-SNAPSHOT
    jar

    save-search-service
    Demo project for Spring Boot

    
        com.example
        spring-cloud
        1.0.0
        ../pom.xml
    

    
        
            org.mybatis
            mybatis
            3.4.6
        

        
            org.mybatis
            mybatis-spring
            1.3.2
        

        
            org.springframework.boot
            spring-boot-starter-jdbc
        

        
            mysql
            mysql-connector-java
            8.0.12
        
    


mybatis配置文件




    
    
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
    


springboot配置文件

 emsp;由于本示例采取注解方式配置数据源,暂不使用spring.datasource前缀

server.port=6789
eureka.client.service-url.defaultZone=http://localhost:1111/eureka
spring.application.name=save-search-service
datasource.url=jdbc:mysql://localhost:3306/spring_cloud?useSSL=true&useUnicode=true&characterEncoding=utf8
datasource.driver-class-name=com.mysql.cj.jdbc.Driver
datasource.username=XXX
datasource.password=XXX

注解配置类

  通过Environment类能够获取到application.properties文件中的配置信息,这里如果采用@Autowire的注入方式可能会注入null值,比较合理的方法是实现EnvironmentAware接口,让spring自动注入Environment。

package com.example.savesearchservice.configuration;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

import lombok.NonNull;

@Configuration
@MapperScan("com.example.savesearchservice.dao")
public class DataSourceConfiguration implements EnvironmentAware {

    private static Log logger = LogFactory.getLog(DataSourceConfiguration.class);

    private Environment environment;

    @Bean
    DataSource dataSource() {
        logger.info("environment:" + environment);
        return DataSourceBuilder.create()
                .url(environment.getProperty("datasource.url"))
                .username(environment.getProperty("datasource.username"))
                .password(environment.getProperty("datasource.password"))
                .driverClassName(environment.getProperty("datasource.driver-class-name"))
                .build();
    }

    @Bean
    SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setConfigLocation(new ClassPathResource("mybatis/mybatis-conf.xml"));
        return sqlSessionFactoryBean.getObject();
    }

    @Bean
    MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setAnnotationClass(com.example.savesearchservice.annotation.DataSource.class);
        mapperScannerConfigurer.setBasePackage("com.example.savesearchservice.dao");
        mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
        return mapperScannerConfigurer;
    }

    @Bean
    DataSourceTransactionManager dataSourceTransactionManager(DataSource dataSource) {
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(dataSource);
        return dataSourceTransactionManager;
    }

    @Override
    public void setEnvironment(@NonNull Environment environment) {
        this.environment = environment;
    }
}

数据库操作接口

package com.example.savesearchservice.dao;

import com.example.savesearchservice.annotation.DataSource;
import com.example.savesearchservice.domain.SaveSearchAlert;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;

import java.util.List;


// create table save_search_alert(
//         id int(11) primary key auto_increment not null,
//         name varchar(255),
//         schedule varchar(255),
//         last_email_time timestamp,
//         create_time timestamp not null default current_timestamp,
//        update_time timestamp not null on update current_timestamp default current_timestamp
//        )ENGINE=InnoDB  DEFAULT CHARSET=utf8;


@DataSource
public interface SaveSearchDao {

    String TABLE = "save_search_alert";

    String ALL_COLUMN = "id,name,schedule,last_email_time,create_time,update_time";


    @Select(""
            + " select " + ALL_COLUMN
            + " from " + TABLE)
    List listAlerts();

    @Insert(""
            + " insert into "
            + TABLE
            + " set "
            + " name = #{name},"
            + " schedule = #{schedule} "
    )
    int insert(SaveSearchAlert saveSearchAlert);
}

你可能感兴趣的:(spring boot整合mybatis)