**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对象时,但是如何签入服务层,如果具有名称的图书存在于数据库中。谁能帮帮我,因为我刚开始穿春靴。
发布于 2022-02-19 05:09:40
您的服务层是设置业务规则的地方,您可以这样做:
RecordExistsExceptionRecordExistsException返回已经存在的书籍时抛出一个findBookByName(String name)。服务类将如下所示:
@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);
}
}https://stackoverflow.com/questions/71182278
复制相似问题