SpringBoot-用yml集成Mybatis

1.导入依赖

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

2.我有一个application-dev.yml和一个applicaion.yml

分别是:

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/study?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    initialSize: 5
    minIdle: 5
    maxActive: 20
    max-wait: 60000
    time-between-eviction-runsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validation-query: SELECT 1 FROM DUAL
    test-while-idle: true
    test-on-borrow: false
    test-on-return: false
    poolPreparedStatements: true
    maxPoolPreparedStatementPerConnectionSize: 20
    filters: stat,wall
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
    useGlobalDataSourceStat: true

mybatis:
  type-aliases-package: ssm.app.model
  # type-handlers-package: com.example.typehandler
  configuration:
  # 驼峰 map-underscore-to-camel-case: true # 打印sql logging: level: ssm.app.mapper : debug
spring:
  profiles:
    active: dev

3.mybatis已经可以用了,下面是mapper接口

@Mapper
public interface CountryMapper {

    @Select("select * from Country")
    public List<Country> selectAll();

    @Select("select * from Country where id = #{id}")
    public Country selectCountryById(long id);
}

service:

@Service
public class CountryServiceImpl implements CountryService {
    @Autowired
    private CountryMapper countryMapper;

    @Override
    public List<Country> getCountriesFromDb() {
        return countryMapper.selectAll();
    }

    @Override
    public Country getCountryFromDbById(long id) {
        return countryMapper.selectCountryById(id);
    }
}

controller:

@RestController
public class CountryController extends BaseController {
    private final CountryService countryServiceImpl;

    @Autowired
    public BaseController(CountryService countryServiceImpl) {
        this.countryServiceImpl = countryServiceImpl;
    }

    @RequestMapping("/getAllCountries")
    public List<Country> getAllCountries() {
        return countryServiceImpl.getCountriesFromDb();
    }
}

ok!还有就是记得注意yml的层次关系,错了然后没看出来,瞎捣鼓然后发现了,再然后就哭了,给自己看的!

猜你喜欢

转载自www.cnblogs.com/KuroNJQ/p/11184178.html
今日推荐