springboot+mybatis

springboot引入mybatis要植入mvn依赖:

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

如果有测试类,则需要添加依赖:

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

同时添加数据库驱动。

如果用xml方式则在 application.properties文件中添加mybatis.xml引入:

mybatis.config-location=classpath:mybatis/mybatis-config.xml

mybatis.mapper-locations=classpath:mybatis/mappings/*.xml

数据库驱动:

spring.datasource.url=jdbc:mysql://127.0.0.1:8080/test
spring.datasource.username=user
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

 在application.java中添加Mapper扫描依赖:

@SpringBootApplication
@MapperScan("com.myapp.*.mapper")
@PropertySource(value="classpath:./myfile/application.properties",encoding="UTF-8")

在mapper包中创建接口:

@Mapper
public interface DistrictMappers {
    
    @Select(value = { "select code, name, PARENT_CODE parentCode from district where parent_code = #{parentCode} order by code asc"})
    public List<DistrictDTO> getDistrictList(@Param(value="parentCode")String parentCode);

 ※注意:当有超过1个参数时,一定要设置 @Param,要不然ibatis不会给你自动匹配,而报出错误BindException.

log控制:

           在springboot的yml中配置mybatis的sql打印:

mybatis:
 
    configuration:
 
        log-impl: org.apache.ibatis.logging.stdout.StdOutImpl  打印输入输出
       log-impl:org.apache.ibatis.logging.log4j.Log4jImpl    仅打印查询输入

参照:ogImpl可选的值有:SLF4J、LOG4J、LOG4J2、JDK_LOGGING、COMMONS_LOGGING、STDOUT_LOGGING、NO_LOGGING 

http://www.mybatis.org/mybatis-3/logging.html

原文地址:https://www.cnblogs.com/DennyZhao/p/9714933.html