这个博客用来记录使用Maven创建一个SpringBoot项目并且集成Mybatis,今天因为网络问题SpringBoot的脚手架不太好使了,集成Mybatis又因为愚蠢的错误搞了半天,特此记录一下。
一、使用Maven创建一个SpringBoot项目
1、首先不使用骨架创建一个项目
2、补充目录结构
3、补充pom.xml文件
在此,因为要进行mybatis的集成,一共引入了web、jdbc、mybatis、mysql连接驱动四个启动器。
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.5.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
</dependencies>
4、添加引导类
package com.xsh.producer;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ProducerApplication {
public static void main(String[] args) {
SpringApplication.run(ProducerApplication.class,args);
}
}
至此,使用Maven创建一个SpringBoot项目就完成了。
二、SpringBoot集成Mybatis
1、配置Application.yml文件
server:
port: 8081 #服务器端口
spring:
datasource:
url: jdbc:mysql:///mycloud?serverTimezone=UTC
username: root
password: root #连接驱动的参数
mybatis:
mapper-location: classpath*:com/xsh/producer/mapper/*.xml #mapper映射文件的地址扫描
type-aliases-package: com.xsh.producer.pojo #操作的实体目录别名配置
2、注入mapper接口
在SpringBoot中将mapper接口注入到Spring容器中需要两个步骤:第一使用@Repository注解进行注入,第二要在引导类上配置扫描@MapperScan
①使用@Repository注解进行注入
package com.xsh.producer.mapper;
import com.xsh.producer.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
@Repository
public interface UserMapper {
User findByUserid(@Param("uid") Integer uid);
}
②在引导类上使用@MapperScan注解进行扫描mapper
package com.xsh.producer;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan(basePackages = {"com.xsh.producer.mapper"})
public class ProducerApplication {
public static void main(String[] args) {
SpringApplication.run(ProducerApplication.class,args);
}
}
至此,SpringBoot集成Mybatis就完成了。