快速搭建Spring boot+Maven+Mybatis项目

打开编译工具,新建项目,我用的是idea,可以直接建Springboot项目,其他的很多编译工具就需要到官网去下载demo了

1:点击next

快速搭建Spring boot+Maven+Mybatis项目

2:修改你的项目名,当然不改也无所谓啦

快速搭建Spring boot+Maven+Mybatis项目

3:选择你要集成的技术,这里我只选了MySQL和Mybatis

快速搭建Spring boot+Maven+Mybatis项目

然后就next就好了

快速搭建Spring boot+Maven+Mybatis项目

项目建完后的样子

点开配置文件

快速搭建Spring boot+Maven+Mybatis项目

我的个人习惯,把配置文件的后缀名改为  .yml,不改也无所谓,只是写法不一样而已

配置阿里巴巴数据源

快速搭建Spring boot+Maven+Mybatis项目

自己按照实际情况修改url等,具体的代码:

图中没有显示的mybatis的配置,使用来把数据库中的蛇形字段自动转为驼峰的配置,

例如数据库中的字段为:user_name则对应转为实体中的userName

server:
    port: 8080

spring:
    datasource:
        name: test
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8
        username: root
        password: root
        type: com.alibaba.druid.pool.DruidDataSource

mybatis:
  mapper-locations: classpath*:com/example/chenpengfu/mapper/*.java
  configuration:
     mapUnderscoreToCamelCase: true

下一步点开pom.xml文件去添加依赖,Springboot的所有需要用到的依赖都在这里配置

快速搭建Spring boot+Maven+Mybatis项目

在pom文件上加入我们需要的阿里巴巴数据源依赖:

快速搭建Spring boot+Maven+Mybatis项目

具体依赖代码:

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.0</version>
</dependency>

配置完之后,项目还跑不起来的,需要在启动类application中注册我们配置的数据源为javabean

快速搭建Spring boot+Maven+Mybatis项目

配置完的视图:

圈出来的时需要注意的引入的包,别引错了

快速搭建Spring boot+Maven+Mybatis项目

具体配置代码:

@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource druidDataSource() {
    DruidDataSource druidDataSource = new DruidDataSource();
    return druidDataSource;
}

搞完这些配置之后回到application.yml文件

可以看到已经不报错了

快速搭建Spring boot+Maven+Mybatis项目

项目搭建到这里还没有正式的完成,既然是集成Mybatis,就需要再配置项目自动扫描Mybatis下的mapper的配置

在项目中新建你的实体类包与mapper包,在启动类开启Mybatis下的mapper扫描

快速搭建Spring boot+Maven+Mybatis项目

具体代码:

@SpringBootApplication(scanBasePackages = "com.example.chenpengfu")
@ComponentScan("com.example.chenpengfu")
@MapperScan("com.example.chenpengfu.mapper")

实体类:对应你的数据表结构

快速搭建Spring boot+Maven+Mybatis项目

mapper包下的类例子,我用的是注解式的写法,有的人习惯xml的写法,但我个人觉得比较麻烦

快速搭建Spring boot+Maven+Mybatis项目

写个测试方法,去调用一下,Spring boot项目建好之后会自动集成了JUnit,可以直接用

快速搭建Spring boot+Maven+Mybatis项目

点击方法体左边的绿色按钮,运行测试方法得到结果输出

快速搭建Spring boot+Maven+Mybatis项目

到这里一个简单的SpringBoot集成Mybatis的框架就搭好了