概述
废话不多说了,直接撸吧 ,先看看整体的结构 【 Spring Boot 2.1.2 , MyBatis 1.3.2 , Mysql 8.0.13 】
搭建Spring Boot工程 Version 2.1.2.RELEASE
pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.2.RELEASE</version> <relativePath /> <!-- lookup parent from repository --> </parent> <groupId>com.artisan</groupId> <artifactId>springbootMybatis</artifactId> <version>0.0.1-SNAPSHOT</version> <name>springbootMybatis</name> <description>Artisan </description> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <!-- spring-boot-starter-web --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- 对JDBC数据库的支持 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <!-- mysql的驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!-- mybatis的starter --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency> <!-- 消除 Java 的冗长 ,优雅的编程 --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <!--开发环境热部署插件 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> <!-- 测试 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
pom中每个jar包都加了注释,这里就不啰嗦了。
application.yml 数据库的配置
# datasource spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver # JDBC连接Mysql6以上com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/artisan?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false username: root password: root
通过上面的属性配置数据库的连接信息后, Spring Boot 就可以自动配置数据源了
集成Mybatis
Step1 添加依赖mybatis- spring-boot- starter
刚才的pom中已经有了,如下
<!-- mybatis的starter --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency>
Step2 库表及domain类
为了方便演示,新建库表和对应的实体类
-- ---------------------------- -- Table structure for artisan -- ---------------------------- DROP TABLE IF EXISTS `artisan`; CREATE TABLE `artisan` ( `id` int(9) NOT NULL AUTO_INCREMENT, `name` varchar(255) DEFAULT NULL, `sex` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of artisan -- ---------------------------- INSERT INTO `artisan` VALUES ('1', 'artisan', '男'); INSERT INTO `artisan` VALUES ('2', '程序媛', '女'); INSERT INTO `artisan` VALUES ('3', '周杰伦', '男'); INSERT INTO `artisan` VALUES ('4', '小笼包', '女'); INSERT INTO `artisan` VALUES ('5', '巨石强森', '男');
com.artisan.model包下新建Artisan实体类
package com.artisan.model; import lombok.Data; /** * * @author yangshangwei * * lombok的注解 @Data 注解在类上 提供类所有属性的 getting 和 setting 方法, * 此外还提供了equals、canEqual、hashCode、toString 方法 * */ @Data public class Artisan { private Long id; private String name; private String sex; }
Step3 添加ArtisanMapper接口
com.artisan.mapper包下新建接口 ArtisanMapper
package com.artisan.mapper; import java.util.List; import org.apache.ibatis.annotations.Mapper; import com.artisan.model.Artisan; /** * * @author yangshangwei * * 增加@Mapper这个注解之后,Spring 启动时会自动扫描该接口,这样就可以在需要使用时直接注入 Mapper 了 */ @Mapper public interface ArtisanMapper { /** * 查询全部数据 */ List<Artisan> selectArtisan(); }
使用了@ Mapper 注解, 增加这个注解之后,Spring 启动时会自动扫描该接口,这样就可以在需要使用时直接注入 Mapper 了
Step4 添加SQL映射文件
在 src/main/resources下面创建mapper目录,然后新建 ArtisanMapper.xml映射文件
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <!-- 当Mapper接口和XML文件关联的时候, namespace的值就需要配置成接口的全限定名称 --> <mapper namespace="com.artisan.mapper.ArtisanMapper"> <select id="selectArtisan" resultType="Artisan"> <!-- resultType可以不用写全,与application.yml中的type-aliases-package属性组合使用 --> select id , name ,sex from artisan </select> </mapper>
Step5 application.yml中配置mybatis
增加如下Mybatis的配置
#mybatis mybatis: # 映射文件的路径 ,支持 Ant 风格的通配符, 多个配置可以使用英文逗号隔开 mapper-locations: classpath:mapper/*.xml # 类型别名包画配置,只能指定具体的包,多个配置可以使用英文逗号隔开 type-aliases-package: com.artisan.model # Mybatis SQL语句控制台打印 configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
Step6 Service层编写
接口和实现类
package com.artisan.service; import java.util.List; import com.artisan.model.Artisan; public interface ArtisanService { List<Artisan> getArtisanList(); }
package com.artisan.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.artisan.mapper.ArtisanMapper; import com.artisan.model.Artisan; import com.artisan.service.ArtisanService; @Service public class ArtisanServiceImpl implements ArtisanService { @Autowired private ArtisanMapper artisanMapper; @Override public List<Artisan> getArtisanList() { return artisanMapper.selectArtisan(); } }
Step7 约定后台返回规范(可省略)
使用泛型封装下返回结果,见注释。 第二个包装类CodeMsg 用了lombok的注解,可以不用。Result没用,仅仅是演示下。。。
package com.artisan.result; public class Result<T> { private int code; private String msg; private T data; /** * 成功时候的调用 * */ public static <T> Result<T> success(T data){ return new Result<T>(data); } /** * 失败时候的调用 * */ public static <T> Result<T> error(CodeMsg cm){ return new Result<T>(cm); } private Result(T data) { this.code = 0; this.msg = "success"; this.data = data; } private Result(CodeMsg cm) { if(cm == null) { return; } this.code = cm.getCode(); this.msg = cm.getMsg(); } public int getCode() { return code; } public String getMsg() { return msg; } public T getData() { return data; } }
package com.artisan.result; import lombok.Getter; public class CodeMsg { @Getter private int code; @Getter private String msg; // 通用异常 public static CodeMsg SUCCESS = new CodeMsg(0, "success"); public static CodeMsg SERVER_ERROR = new CodeMsg(-1, "服务端异常"); private CodeMsg(int code, String msg) { this.code = code; this.msg = msg; } }
Step8 Controller编写
package com.artisan.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import com.artisan.model.Artisan; import com.artisan.result.CodeMsg; import com.artisan.result.Result; import com.artisan.service.ArtisanService; @RestController public class ArtisanController { @Autowired private ArtisanService artisanService; @GetMapping("/test") public String test() { return "artisan test"; } // 正常情况 @GetMapping("/artisans") public Result<List<Artisan>> selectAllArtisan() { return Result.success(artisanService.getArtisanList()); } // 模拟异常情况 @GetMapping("/artisansError") public Result<List<Artisan>> selectAllArtisanError() { return Result.error(CodeMsg.SERVER_ERROR); } }
Step9 测试
比较简单,各层的单元测试就不写了,直接启动测试吧
启动spring boot 工程
访问 http://localhost:8080/artisans
日志:
访问 http://localhost:8080/artisansError
代码
https://github.com/yangshangwei/springbootMybatis