springboot+mybatis

本文详细介绍了如何在SpringBoot项目中引入MyBatis,包括添加必要的Maven依赖、配置数据库连接、使用XML映射文件、配置日志打印以及在代码中实现Mapper接口的方法。

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-locaitons=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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值