spring 和 mybatis 整合的那篇: . 配置文件比ssm(1) 更多, 在做项目的时候, 配置文件是一个让人头大的事情.
那么在spring boot中, 实现相同功能, 需不需要做那么多配置呢.
一. 从pom.xml 开始
4.0.0 org.elvin boot 0.0.1-SNAPSHOT jar boot Demo project for Spring Boot org.springframework.boot spring-boot-starter-parent 1.5.9.RELEASE UTF-8 UTF-8 1.8 org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-starter-thymeleaf org.springframework.boot spring-boot-devtools true org.springframework.boot spring-boot-starter-data-jpa mysql mysql-connector-java 5.1.6 joda-time joda-time 2.6 org.springframework.boot spring-boot-maven-plugin
pom.xml文件, 直观的感觉, 就是非常的短, 非常的少. 简洁
二. 配置文件
#配置项目端口和根路径server: port: 8080 context-path: /bootspring: 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: falselogging: 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{/* @Query() public Page 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 ListfindAll(); 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: */@Servicepublic class BookServiceImpl implements BookService { @Autowired private BookRepository bookRepository; @Override public ListfindAll(){ List 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; }}
七. 结果
首先新增一条数据, 然后再查询出来, 没有啥问题. 然后调用同样的方法, 修改数据