Spring boot + Mybatis + SQLite 搭建blog API
一、准备环境
二、创建一个SpringBoot项目
在此我就不再演示如何创建SpringBoot项目了,需要的请看【 码出精彩人生】这位大佬的博客
三、在pom.xml文件中添加所需要的依赖jar
使用sqlite数据库需要引入sqlite-jdbc.jar包
<!-- SQLite 驱动 -->
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>3.21.0.1</version>
</dependency>
pom.xml文件依赖如下
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- SQLite 驱动 -->
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>3.21.0.1</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.22</version>
</dependency>
</dependencies>
四、创建sqlite数据库
1、在项目的根目录下创建文件 blog-db.sqlite (名字随便起)
2、然后在IDEA右边边上有一个Database,点击创建SQLite数据库
3、File-->>选择第一步创建的 blog-db.sqlite ,然后点击Test Connection 测试是否连接成功
4、创建 d_user 表
(1) 控制台创建表
拷贝下面创建表语句,执行即可创建表
create table d_users
(
id int
constraint "d-users_pk"
primary key,
username text not null,
password text not null,
start int default 1 not null,
foundTime text
);
(2)手动创建
五、一切准备就绪开始写业务。
1、添加配置文件application.yaml
把创建项目生成的.properties配置文件删除,创建一个 application.yaml,配置文件放在 resources 目录下
server:
port: 8989 # 端口号
spring:
datasource:
url: jdbc:sqlite:D:/Software/PycharmProjects/d-blog/blog-db.sqlite # 创建的sqlite数据库所在路径
username: # 因为没有用户名和密码,所以这两个参数就没有值
password:
driver-class-name: org.sqlite.JDBC # sqlite驱动
# mybatis配置
mybatis:
mapper-locations: classpath:mybatis/mapper/*Mapper.xml # 配置mapper.xml文件路径
type-aliases-package: com.desire.entity # 实体类包名
# mybatis 打印SQL, 配置后就会在控制台打印执行的SQL语句
logging:
level:
com.desire.mapper: debug
2、根据数据库表创建实体类--UserEntity.java
package com.desire.entity;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
public class UserEntity {
private int id;
private String userName;
private String password;
private int start;
private String foundTime;
}
3、在resources/mybatis/mapper中创建--UserMapper.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 namespace="com.desire.mapper.UserMapper">
<resultMap id="BaseResultMap" type="com.desire.entity.UserEntity">
<result column="id" jdbcType="INTEGER" property="id" />
<result column="userName" jdbcType="VARCHAR" property="userName" />
<result column="password" jdbcType="VARCHAR" property="password" />
<result column="start" jdbcType="INTEGER" property="start" />
<result column="foundTime" jdbcType="VARCHAR" property="foundTime" />
</resultMap>
<select id="findUserById" resultType="com.desire.entity.UserEntity">
select * from d_users where id = #{id}
</select>
<select id="findUserAll" resultMap="BaseResultMap" resultType="com.desire.entity.UserEntity">
select * from d_users
</select>
</mapper>
4、创建mapper接口--UserMapper.java
package com.desire.mapper;
import com.desire.entity.UserEntity;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface UserMapper {
UserEntity findUserById(int id);
List<UserEntity> findUserAll();
}
5、创建service实现mapper接口--UserService.java
package com.desire.service;
import com.desire.entity.UserEntity;
import com.desire.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserService implements UserMapper {
@Autowired
private UserMapper userMapper;
@Override
public UserEntity findUserById(int id){
return userMapper.findUserById(id);
}
@Override
public List<UserEntity> findUserAll() {
return userMapper.findUserAll();
}
}
6、创建Controller--UserController.java
package com.desire.controller;
import com.desire.common.Result;
import com.desire.common.ResultUtil;
import com.desire.entity.UserEntity;
import com.desire.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
@ResponseBody
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("getUser/{id}")
public Result<UserEntity> getUser(@PathVariable int id) {
return ResultUtil.success(userService.findUserById(id));
}
@RequestMapping("getUsers")
public Result<UserEntity> getUsers() {
return ResultUtil.success(userService.findUserAll());
}
}
7、规范化封装统一返回数据格式
1)定义http请求返回的最外层对象,封装返回数据的统一格式 --Result.java
package com.desire.common;
/**
* http请求返回的最外层对象
* @param <T>
*/
public class Result<T> {
/**
* 错误码.
*/
private Integer code;
/**
* 提示信息.
*/
private String msg;
/**
* 具体的内容.
*/
private T data;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
2) 为了统一管理返回数据结果code和message,新建一个枚举类ResultEnum.java
package com.desire.common;
public enum ResultEnum {
UNKONW_ERROR(1001, "未知错误"),
SUCCESS(200, "成功")
;
private Integer code;
private String msg;
ResultEnum(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
public Integer getCode() {
return code;
}
public String getMsg() {
return msg;
}
}
3) 为了防止多次出现new Result()的代码造成冗余,增加一个工具类ResultUtil.java
package com.desire.common;
/**
* 为了避免上面出现的代码冗余情况,应该增加工具类,封装请求失败和成功时候的方法,这里可使用静态方法
*/
public class ResultUtil {
public static Result success(Object object) {
Result result = new Result();
result.setCode(ResultEnum.SUCCESS.getCode());
result.setMsg(ResultEnum.SUCCESS.getMsg());
result.setData(object);
return result;
}
public static Result success() {
return success(null);
}
public static Result error(Integer code, String msg) {
Result result = new Result();
result.setCode(code);
result.setMsg(msg);
return result;
}
}
六、启动项目,验证写的是否正确--成功
七、写在最后
这个例子只实现了两个接口
- 根据id查找用户: http://localhost:8989/user/getUser/2
- 查询全部用户: http://localhost:8989/user/getUsers
最近在写一个博客相关的项目,前端vue部分已经完成(感觉写的很low),不过还有待继续改进,我也在继续学习vue,所用接口,用的是json server 做的服务。
有兴趣的可以看下,提点意见,【personal_blog】
这个SpringBoot项目就是我做的博客的接口服务,后续要把前端中的json server换成真实的接口。持续更新中,写的不好请给我提些建议。感谢看到最后。