本篇的是对Jpa的增删改查的使用
一、建库建表
book表和category中室友朱外键关系的----需要先建category表再建book表
先贴出表结构
user表
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` char(255) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
category表
DROP TABLE IF EXISTS `category`;
CREATE TABLE `category` (
`id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
book表
DROP TABLE IF EXISTS `book`;
CREATE TABLE `book` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`cover` varchar(255) DEFAULT '',
`title` varchar(255) NOT NULL DEFAULT '',
`author` varchar(255) DEFAULT '',
`date` varchar(20) DEFAULT '',
`press` varchar(255) DEFAULT '',
`abs` varchar(255) DEFAULT NULL,
`cid` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fk_book_category_on_cid` (`cid`),
CONSTRAINT `fk_book_category_on_cid` FOREIGN KEY (`cid`) REFERENCES `category` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=102 DEFAULT CHARSET=utf8;
二、增删改查
本章需要构建以下文件
1.pojo类
Category:
package com.example.wei.pojo;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import javax.persistence.*;
@Entity
@Table(name = "book")
@JsonIgnoreProperties({"handler","hibernateLazyInitializer"})
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
int id;
@ManyToOne
@JoinColumn(name = "cid")
private Category category;
String cover;
String title;
String author;
String date;
String press;
String abs;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public String getCover() {
return cover;
}
public void setCover(String cover) {
this.cover = cover;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getPress() {
return press;
}
public void setPress(String press) {
this.press = press;
}
public String getAbs() {
return abs;
}
public void setAbs(String abs) {
this.abs = abs;
}
}
Book:
package com.example.wei.pojo;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import javax.persistence.*;
@Entity
@Table(name = "category")
@JsonIgnoreProperties({"handler","hibernateLazyInitializer"})
public class Category {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
int id;
String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
2.Dao层
BookDao
package com.example.wei.dao;
import com.example.wei.pojo.Book;
import com.example.wei.pojo.Category;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface BookDao extends JpaRepository<Book,Integer> {
List<Book> findAllByCategory(Category category);
List<Book> findAllByTitleLikeOrAuthorLike(String keyword1, String keyword2);
}
这个 DAO 不需要额外构造的方法,JPA 提供的默认方法就够用了。
CategoryDao:
package com.example.wei.dao;
import com.example.wei.pojo.Category;
import org.springframework.data.jpa.repository.JpaRepository;
public interface CategoryDao extends JpaRepository<Category,Integer> {
}
3.Service 层
这个 Service 提供了四个功能,分别是查出所有书籍、增加或更新书籍、通过 id 删除书籍和通过分类查出书籍。
ave() 方法的作用是,当主键存在时更新数据,当主键不存在时插入数据。
BookService:
package com.example.wei.service;
import com.example.wei.dao.BookDao;
import com.example.wei.pojo.Book;
import com.example.wei.pojo.Category;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class BookService {
@Autowired
BookDao bookDao;
@Autowired
CategoryService categoryService;
public List<Book> list(){
Sort sort = Sort.by(Sort.Direction.DESC, "id");
return bookDao.findAll(sort);
}
public void addOrUpdate(Book book){
bookDao.save(book);
}
public void deleteById(int id){
bookDao.deleteById(id);
}
public List<Book> listByCategory(int cid){
Category category = categoryService.get(cid);
return bookDao.findAllByCategory(category);
}
}
CategoryService:
package com.example.wei.service;
import com.example.wei.dao.CategoryDao;
import com.example.wei.pojo.Category;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class CategoryService {
@Autowired
CategoryDao categoryDao;
public List<Category>list(){
Sort sort = Sort.by(Sort.Direction.DESC, "id");
return categoryDao.findAll(sort);
}
public Category get(int id) {
Category c= categoryDao.findById(id).orElse(null);
return c;
}
}
4.Controller层
在 Controller 层里我们继续写需要的 API
package com.example.wei.controller;
import com.example.wei.pojo.Book;
import com.example.wei.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
public class LibraryController {
@Autowired
BookService bookService;
@GetMapping("api/books")
public List<Book> list() throws Exception{
return bookService.list();
}
@PostMapping("api/books")
public Book addOrUpdateBooke (@RequestBody Book book) throws Exception{
bookService.addOrUpdate(book);
return book;
}
@PostMapping("/api/delete")
public void delete(@RequestBody Book book) throws Exception{
bookService.deleteById(book.getId());
}
@GetMapping("/api/categories/{cid}/books")
public List<Book> listByCategory(@PathVariable("cid")int cid) throws Exception{
if(0 != cid){
return bookService.listByCategory(cid);
}else{
return list();
}
}
}
5.测试接口
首先是查询所有书籍,访问 http://localhost:8888/api/books
,结果如下: