spring 和 mybatis 整合的那篇: ssm(2) . 配置文件比ssm(1) 更多, 在做项目的时候, 配置文件是一个让人头大的事情.
那么在spring boot中, 实现相同功能, 需不需要做那么多配置呢.
一. 从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> <groupId>org.elvin</groupId> <artifactId>boot</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>boot</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <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> <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> <!--view : thymeleaf模板--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> <!--db : 数据库相关--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.6</version> </dependency> <!--tools : joda-time--> <dependency> <groupId>joda-time</groupId> <artifactId>joda-time</artifactId> <version>2.6</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
pom.xml文件, 直观的感觉, 就是非常的短, 非常的少. 简洁
二. 配置文件
#配置项目端口和根路径 server: port: 8080 context-path: /boot spring: datasource: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql:///test?useUnicode=true&characterEncoding=utf-8 username: root password: root jpa: hibernate: ddl-auto: update show-sql: true thymeleaf: cache: false logging: level: warn file: ./boot.log
三. 实体类
package org.elvin.boot.pojo; import javax.persistence.*; /** * author: Elvin * Date: 2017/12/4 15:37 * Description: */ @Entity @Table(name="book") public class Book { @Id @GeneratedValue private Integer id; private String name; private String publishTime; private Integer price; @Override public String toString() { return "Book{" + "id=" + id + ", name=‘" + name + ‘\‘‘ + ", publishTime=‘" + publishTime + ‘\‘‘ + ", price=" + price + ‘}‘; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPublishTime() { return publishTime; } public void setPublishTime(String publishTime) { this.publishTime = publishTime; } public Integer getPrice() { return price; } public void setPrice(Integer price) { this.price = price; } }
通过注解, 可以映射到数据中的表. 由于在前面设置了 ddl-auto:update , 那么在每次启动的时候, 都会去检测数据库, 是否有这张表, 如果没有, 则会新增, 如果有, 则会修改表.
四. Repository
package org.elvin.boot.repository; import org.elvin.boot.pojo.Book; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; /** * author: Elvin * Date: 2017/12/5 16:58 * Description: */ public interface BookRepository extends JpaRepository<Book, Integer> { /* @Query() public Page<Book> myQuery();*/ }
这里使用的并不是 mybatis 的写sql的方式, 但是很大一部分的表操作, jpa 标准 都可以完成, 如果想写自定义sql, 可以通过方法上加 @Query 注解的方式来写.
五. service 和实现类
package org.elvin.boot.service; import org.elvin.boot.pojo.Book; import java.util.List; public interface BookService { public List<Book> findAll(); public Book findOne(Integer id); public void put(Book book); public void remove(Integer id); }
package org.elvin.boot.serviceimpl; import org.elvin.boot.pojo.Book; import org.elvin.boot.pojo.PageInfo; import org.elvin.boot.repository.BookRepository; import org.elvin.boot.service.BookService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.stereotype.Service; import java.util.List; /** * author: Elvin * Date: 2017/12/5 17:03 * Description: */ @Service public class BookServiceImpl implements BookService { @Autowired private BookRepository bookRepository; @Override public List<Book> findAll(){ List<Book> list = bookRepository.findAll(); return list; } @Override public Book findOne(Integer id){ Book book = bookRepository.findOne(id); return book; } @Override public void put(Book book) { bookRepository.save(book); } @Override public void remove(Integer id) { bookRepository.delete(id); } }
put在这里, 承担 新增 和 修改 的责任. 不管是新增还是修改, 都是调用的 jpa的save方法.
区别在于, 是否传入了id.
没有传id -> 直接新增
传入了id -> 根据id进行查询 -> 没有数据 -> 新增
|-> 有数据 -> 修改
六. controller
返回数据格式, 稍微做了一下封装.
package org.elvin.boot.pojo; public interface ResStatus { String SUCCESS = "success"; String FAIL = "fail"; String ERROR = "error"; }
package org.elvin.boot.pojo; /** * author: Elvin * Date: 2017/12/6 10:40 * Description: */ public class ResObj { private String msg; private Integer Code; private Object obj; public ResObj() { } public ResObj(String msg, Integer code, Object obj) { this.msg = msg; Code = code; this.obj = obj; } @Override public String toString() { return "ResObj{" + "msg=‘" + msg + ‘\‘‘ + ", Code=" + Code + ", obj=" + obj + ‘}‘; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public Integer getCode() { return Code; } public void setCode(Integer code) { Code = code; } public Object getObj() { return obj; } public void setObj(Object obj) { this.obj = obj; } }
再来看controller.
package org.elvin.boot.controller; import org.elvin.boot.pojo.Book; import org.elvin.boot.pojo.ResObj; import org.elvin.boot.pojo.ResStatus; import org.elvin.boot.service.BookService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; /** * author: Elvin * Date: 2017/12/6 10:36 * Description: */ @RestController @RequestMapping("third") public class ThirdController { private Logger logger = LoggerFactory.getLogger(ThirdController.class); @Autowired private BookService bookService; @PostMapping("put") public ResObj put(Book book){ ResObj res = new ResObj(ResStatus.FAIL, 0, null); try{ bookService.put(book); res.setMsg(ResStatus.SUCCESS); res.setCode(1); res.setObj(book); } catch (Exception e){ logger.error(e.getMessage()); } return res; } @PostMapping("delete/{id}") public ResObj delete(@PathVariable Integer id){ ResObj res = new ResObj(ResStatus.FAIL, 0, null); try{ bookService.remove(id); res.setMsg(ResStatus.SUCCESS); res.setCode(1); } catch (Exception e){ logger.error(e.getMessage()); } return res; } @RequestMapping(value = "getAll", method = {RequestMethod.GET, RequestMethod.POST }) public ResObj getAll(){ ResObj res = new ResObj(ResStatus.FAIL, 0, null); try{ res.setObj(bookService.findAll()); res.setMsg(ResStatus.SUCCESS); res.setCode(1); } catch (Exception e){ logger.error(e.getMessage()); } return res; } @RequestMapping(value = "getById/{id}", method = {RequestMethod.GET, RequestMethod.POST }) public ResObj getById(@PathVariable Integer id){ ResObj res = new ResObj("fail", 0, null); try{ res.setObj(bookService.findOne(id)); res.setMsg(ResStatus.SUCCESS); res.setCode(1); /*int a = 0; int c = 1 / a;*/ } catch (Exception e){ logger.error(e.getMessage()); } return res; } }
七. 结果
首先新增一条数据, 然后再查询出来, 没有啥问题. 然后调用同样的方法, 修改数据
时间: 2024-10-23 19:39:53