首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何检查spring引导post API是否在数据库中可用

如何检查spring引导post API是否在数据库中可用
EN

Stack Overflow用户
提问于 2022-02-19 04:53:59
回答 1查看 451关注 0票数 0
代码语言:javascript
复制
**Controller**
package com.example.curd.curdtesting.controller;

import com.example.curd.curdtesting.entity.Book;
import com.example.curd.curdtesting.service.BookServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class Controller {
    @Autowired
    BookServiceImpl bookService;
  
    @PostMapping("/addProducts")
    public List<Book> addProducts(@RequestBody List<Book> book) {
        return bookService.insertBook(book);
    }
}

**Entity class**
package com.example.curd.curdtesting.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
@Table
public class Book {
    @Id
    @GeneratedValue
    private int id;
    private String name;
    private String description;

}

**Service class**

package com.example.curd.curdtesting.service;

import com.example.curd.curdtesting.entity.Book;
import com.example.curd.curdtesting.repository.BookRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class BookServiceImpl {
    @Autowired
    BookRepo bookRepo;

     public List<Book> insertBook(List<Book> book) {

       return bookRepo.saveAll(book);
    }
}

**Repository**

package com.example.curd.curdtesting.repository;
import com.example.curd.curdtesting.entity.Book;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

public interface BookRepo extends JpaRepository<Book, Integer> {
    public List<Book> findBookByName(String name);
}

一旦收到用户的json格式的项目。我想要检查我的数据库中是否已经有同名的书,如果是的话,我想要输出副本不可能。当我从json接收到book对象时,但是如何签入服务层,如果具有名称的图书存在于数据库中。谁能帮帮我,因为我刚开始穿春靴。

EN

回答 1

Stack Overflow用户

发布于 2022-02-19 05:09:40

您的服务层是设置业务规则的地方,您可以这样做:

  1. 创建一个自定义异常来处理逻辑,例如:RecordExistsException
  2. 创建一个RestControllerAdvice来处理异常。在这个类中,可以返回异常引发的消息。
  3. 检查您的记录是否存在,并在您的RecordExistsException返回已经存在的书籍时抛出一个findBookByName(String name)

服务类将如下所示:

代码语言:javascript
复制
@Service
public class BookServiceImpl {
    @Autowired
    BookRepo bookRepo;

     public List<Book> insertBook(Book book) {
       if(!bookRepo.findByName(book.getName()).isEmpty()) {
           throw new RecordExistsException("The book " + book.getName() + " already exists !!!")
       }
       return bookRepo.saveAll(book);
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71182278

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档