Physical Address
Physical Address
The following demonstrates creating a repository class inside the service package.
The repository interface extends JpaRepository
and is annotated with @Repository
The service interface includes the findById
method.
Below is the BookRepository.java
interface.
package com.codersstash.book_details.repository;
import com.codersstash.book_details.entity.Book;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface BookRepository extends JpaRepository<Book, Integer> {
public Book findById(int book_id) ;
}
The service class is annotated with @Service
.
The service class uses field injection with the @Autowired
annotation to inject the repository.
The service class implements functions such as save
, getById(id)
, getAllData()
, and deleteById(id)
.
Below is the implementation of the BookService.java
class.
BookService.java
package com.codersstash.book_details.service;
import com.codersstash.book_details.entity.Book;
import com.codersstash.book_details.repository.BookRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class BookService {
@Autowired
private BookRepository bookRepository;
public Book saveBook(Book book){
return bookRepository.save(book);
}
public Book getBookById(int book_id){
return bookRepository.findById(book_id);
}
public List<Book> getAllBooks(){
return bookRepository.findAll();
}
public void deleteBook(int id){
bookRepository.deleteById(id);
}
}
You can find the related GitHub repository branch here : book-details-repository