spring 和 mybatis 整合的那篇: ssm(2) . 配置文件比ssm(1) 更多, 在做項目的時候, 配置文件是一個讓人頭大的事情. 那麼在spring boot中, 實現相同功能, 需不需要做那麼多配置呢. 一. 從pom.xml 開始 pom.xml文件, 直觀的感覺, 就是非常的 ...
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; } }
七. 結果
首先新增一條數據, 然後再查詢出來, 沒有啥問題. 然後調用同樣的方法, 修改數據