一、项目目录
二、添加依赖
首先要新建一个SpringBoot项目,要选择web的项目。然后初始化完项目后,我们在pom.xml中添加需要的依赖。
把你的配置下的依赖换成我这个。
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.2.0</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.9</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3.0.0</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> </resource> </resources> </build>
三、代码编写
总的流程是建立数据库 -> 连接数据库 -> 创建对象类 -> 创建业务接口 -> 业务实现类 -> 数据库接口类 -> xml数据库操作 -> 接口类
1、创建数据库
创建一个数据库为book
Create database book;
创建表名也暂为book吧
DROP TABLE IF EXISTS `book`; CREATE TABLE `book` ( `id` int NOT NULL AUTO_INCREMENT, `name_` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, `author` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
同时插入一点数据吧
INSERT INTO `book` VALUES ('1', '121', '张三'); INSERT INTO `book` VALUES ('3', 'ewew', '小王'); INSERT INTO `book` VALUES ('4', 'ewew', '小王1');
到此数据库准备完毕,接下来我们将项目与数据库配置连接。
2、配置连接
打开项目,找到项目下的resources文件夹,然后就会看到application.properties文件,我这里改为了yaml文件作为配置文件。
spring: datasource: url: jdbc:mysql://localhost:3306/book?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC username: root //换成你的用户名 password: 123456 //换成你的密码 driver-class-name: com.mysql.cj.jdbc.Driver
3、创建对象类
在model的包下面,我们创建一个实体类为Book.java
因为我们引入了Lombok依赖,所有只要加一个@Data注解就不用写get/set方法了。节省代码量
package com.mjc.book.model; import lombok.Data; /** * 实体类,对应数据库表 * @author admin */ @Data public class Book { private int id; private String bookName; private String author; }
4、创建业务接口
在包service下面增加一个BookService.java
类,主要放业务的接口,可供controller层调用。
package com.mjc.book.service; import com.mjc.book.model.Book; import java.util.List; /** * controller层调用业务层 * @author admin */ public interface BookService { /** * 查询书 * @return */ List<Book> findAll(); /** * 添加书 * @param book */ void creatBook(Book book); /** * 更新书 * @param book */ void updateBook(Book book); /** * 删除书 * @param id */ void deleteBook(int id); }
5、业务实现类
在service包里再新建一个Impl包,主要放业务实现类,增加一个BookServiceImpl.java
类,继承service接口。
package com.mjc.book.service.Impl; import com.mjc.book.mapper.BookMapper; import com.mjc.book.model.Book; import com.mjc.book.service.BookService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * 业务实现层 * @author admin */ @Service public class BookServiceImpl implements BookService { @Autowired BookMapper bookMapper; @Override public List<Book> findAll() { return bookMapper.findAll(); } @Override public void creatBook(Book book) { bookMapper.insert(book); } @Override public void updateBook(Book book) { bookMapper.update(book); } @Override public void deleteBook(int id) { bookMapper.delete(id); } }
6、 数据库接口类
在mapper包下增加一个接口类BookMapper.java
类
package com.mjc.book.mapper; import com.mjc.book.model.Book; import org.apache.ibatis.annotations.Mapper; import java.util.List; /** * 数据库查询接口mapper相当于dao层 * @author admin */ @Mapper public interface BookMapper { /** * 查询全部图书 * @return */ List<Book> findAll(); /** * 添加图书 * @param book */ void insert(Book book); /** * 更新图书 * @param book */ void update(Book book); /** * 删除书 * @param id * @return */ int delete(int id); }
7、xml数据库操作
同样,在mapper包下增加一个xml配置BookMapper.xml
, BookMapper接口的方法就是xml中增删改查对应的id
<?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.mjc.book.mapper.BookMapper"> <resultMap id="BaseResultMap" type="com.mjc.book.model.Book"> <result column="id" jdbcType="INTEGER" property="id"/> <result column="name_" jdbcType="VARCHAR" property="bookName"/> <result column="author" jdbcType="VARCHAR" property="author"/> </resultMap> <select id="findAll" resultMap="BaseResultMap"> select * from book; </select> <insert id="insert" parameterType="com.mjc.book.model.Book" useGeneratedKeys="true" keyProperty="id"> INSERT INTO book (name_, author) VALUES(#{bookName}, #{author}) </insert> <update id="update" parameterType="com.mjc.book.model.Book"> update book <set> name_ = #{bookName}, author = #{author} </set> WHERE id = #{id} </update> <delete id="delete" parameterType="java.lang.Integer"> delete from book where id = #{id, jdbcType=INTEGER} </delete> </mapper>
8、接口类
在写接口类之前,我们要先写一个返回类,对返回的格式进行统一的封装。在util包中新建一个Result.java
package com.mjc.book.util; import lombok.Data; import java.io.Serializable; /** * 统一返回格式 */ @Data public class Result implements Serializable { //响应码 private int code; private Object obj; public Result(int code) { this.code = code; } public Result() { } public Result success(int code, Object object){ Result result = new Result(); result.setCode(code); result.setObj(object); return result; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } }
然后再新建一个controller包,在包中新建一个controller.java
类。
package com.mjc.book.controller; import com.mjc.book.model.Book; import com.mjc.book.service.BookService; import com.mjc.book.util.Result; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import java.util.List; /** * 接口层,供前端调用 * @author admin */ @Api(tags = "图书管理" ) @RestController @RequestMapping(value = "/book") public class BookController { @Autowired BookService bookService; /** * 获取所有的书 * @return */ @ApiOperation(value = "获取所有的书", notes = "") @GetMapping(value = "/list") public Result bookList(){ List<Book> all = bookService.findAll(); return new Result().success(200, all); } /** * 添加图书 * @param book * @return */ @ApiOperation(value = "添加图书", notes = "") @PostMapping(value = "/save") public Result bookSave(@RequestBody Book book){ bookService.creatBook(book); return new Result().success(200, "成功"); } /** * 更新图书 * @param book * @return */ @ApiOperation(value = "更新图书", notes = "") @PostMapping(value = "/update") public Result bookUpdate(@RequestBody Book book){ bookService.updateBook(book); return new Result().success(200, "成功"); } /** * 删除图书 * @param id * @return */ @ApiOperation(value = "删除图书", notes = "") @PostMapping(value = "/delete/{id}") public Result bookDelete(@PathVariable(value = "id") int id){ bookService.deleteBook(id); return new Result().success(200, "成功"); } }
9、接入Swagger
我这里引入了Swagger接口文档,依赖已经在前面添加了,现在你要在启动类上加一个注解即可。
package com.mjc.book; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import springfox.documentation.oas.annotations.EnableOpenApi; @EnableOpenApi @SpringBootApplication public class BookApplication { public static void main(String[] args) { SpringApplication.run(BookApplication.class, args); } }
源码我已上传到gitee上,地址为:https://gitee.com/xyhwh/book-demo