小白理解springboot集成mybatis

springboot集成mybatis

1. 导入依赖

<dependency>
    <groupId>org.mybatis.spring.bootgroupId>
    <artifactId>mybatis-spring-boot-starterartifactId>
    <version>2.1.1version>
dependency>

<dependency>
    <groupId>mysqlgroupId>
    <artifactId>mysql-connector-javaartifactId>
    <version>5.1.37version>
dependency>

2. 在核心配置文件application.properties中配置mapper.xml所在位置

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

classpath会自动从main/resources/下去找,相当于具体路径其实是main/resources/mapper/*.xml

P.S.

//这个配置是指将带有下划线的表字段映射为驼峰命名格式的实体类属性
mybatis.configuration.map-underscore-to-camel-case=true

3. 在核心配置文件application.properties中配置数据源

spring.datasource.url=jdbc:mysql://localhost:3306/handson?serverTimezone=UTC&useUnico de=true&characterEncoding=utf-8&useSSL=true
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

4. 在mybatis的mapper接口中添加@Mapper注解 或者在运行主类上添加@MapperScan(“com.xxx.xxx.mapper”)注解包扫描

同时也可以采用mybatis generator插件来自动生成mapper,简化操作。

详细步骤可以参考我的SpringBoot实战项目笔记中集成mybatis generator部分。

因为那里采用的是h2数据库,所以这里稍微讲下mysql的一种配置方法。

首先需要将内部对h2的依赖删除,换成文件配置路径。

<plugin>
    <groupId>org.mybatis.generatorgroupId>
    <artifactId>mybatis-generator-maven-pluginartifactId>
    <version>1.4.0version>
    <configuration>
        
        <configurationFile>generatorConfig.xmlconfigurationFile>
        <verbose>trueverbose>
        <overwrite>trueoverwrite>
    configuration>
plugin>

然后在generatorConfig.xml中加入以下语句。


classPathEntry>

然后对文件内jdbc连接换成mysql的形式即可。

最后就是编写service类、controller类,进行常规的测试。

记得一定要加@Mapper和@Service注解,不然spring会找不到bean的实体对象。

你可能感兴趣的:(小白理解springboot集成mybatis)