spring boot에서의 rest api를 구현하고자 한다.
주제는 책이며 id, name, author, publisher의 요소를 갖는다.
Spring Initializr: Create a Gradle Project
Spring Boot version : 3.3.3
Language : Java 17
Group Id : com.book
Artifact Id : rest-sample
Specify packaging type : War
dependencies
spring.application.name=rest-sample
# go에서 임포트 업로드 받고 go init mod 하여 적용하는것 처럼 해당 패키지에 수동으로 입력함
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=update
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
// 테이블 생성
@Entity
@Table(name = "tb_book")
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String author;
private String publisher;
public Book() {
}
public Book(String name, String author, String publisher) {
this.name = name;
this.author = author;
this.publisher = publisher;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
}
public interface BookRepository extends JpaRepository<Book, Long> {
// 메서드쿼리
List<Book> findByName(String name);
// JPQL
// nativeQuery = true라면 연동하는 db에 수동으로 쿼리를 때려박는다
// @Query(value = "SELECT b FROM Book b WHERE b.name Like %:word%") 까지 있다면 자동으로 형식에 맞게 쿼리를 넣어준다
@Query(value = "SELECT b FROM Book b WHERE b.name Like %:word%", nativeQuery = true)
List<Book> findBySameName(@Param("word") String name);
}
@RestController
@RequestMapping("/api/book")
public class BookController {
// 의존성 주입
@Autowired
private BookRepository bookRepository;
@GetMapping
public List <Book> getBooks() {
return bookRepository.findAll();
}
@GetMapping
public List <Book> getBooksByName(@PathVariable("name") String name) {
return bookRepository.findByName(name);
}
@GetMapping
public List <Book> getBooksBySameName(@PathVariable("word") String word) {
return bookRepository.findBySameName(word);
}
@PostMapping
// RequestBody : 바디 파라미터를 매개변수로 받아서 사용
public Book createBook(@RequestBody Book book) {
// save : 저장한 것을 리턴까지 해주는 메서드
return bookRepository.save(book);
}
@PutMapping("/{id}")
// PathVariable : 패스파라미터로 id를 받음
public Book updateUser(@PathVariable("id") Long id, @RequestBody Book bookInfo) {
// id로 book을 get하고
Book book = bookRepository.findById(id).get();
// book의 요소들을 bookInfo에 입력한 내용으로 대입
book.setName(bookInfo.getName());
book.setAuthor(bookInfo.getAuthor());
book.setPublisher(bookInfo.getPublisher());
// 대입한 내용 저장
return bookRepository.save(book);
}
@DeleteMapping("/{id}")
public void deleteUser(@PathVariable("id") Long id) {
bookRepository.deleteById(id);
}
}