6.6 實作一個 Service Layer
1.我們先定義出一個 Service Java 介面,用來針對 Book 進行 CRUD 料庫的存取操作。
程式源碼如下 :
package edume.microservice.service;
import java.util.Map;
import edume.microservice.model.Book;
public interface IBookService
{
public Map<String, Object> createBook(Map<String, Object> bookMap);
public Map<String, Object> editBook(String bookId, Map<String, Object> bookMap);
public Map<String, String> deleteBook(String bookId);
public Book getBookDetails(String bookId);
public Map<String, Object> getAllBooks();
}
2.實作上述 IBookService 介面。
源碼如下 :
package edume.microservice.service;
import java.util.List;.
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import edume.microservice.model.Book;
import edume.microservice.repository.BookRepository;
@Service
public class BookService implements IBookService
{
private Log logger = LogFactory.getLog(BookService.class);
@Autowired
private BookRepository bookRepository = null;
@Override
public void createBook(Book book)
{
this.bookRepository.save(book);
}
public void updateBook(Book book)
{
this.bookRepository.save(book);
}
@Override
public Book getBook(String bookId)
{
return this.bookRepository.findOne(bookId);
}
@Override
public List<Book> getAllBooks()
{
return this.bookRepository.findAll();
}
@Override
public void deleteBook(String bookId)
{
this.bookRepository.delete(bookId);
}
}