簡體   English   中英

自定義存儲庫行為Spring-Boot

[英]Customizing Repository behavior Spring-Boot

我想向我的存儲庫添加自定義行為,例如,我想添加一種保存並記錄我的實體的方法,這就是我的存儲庫:

@Repository
public interface BookRepository extends JpaRepository<Book, Long>, BookRepositoryCustom {

    Book findByTitle(String bookName);

}

這是我的自定義倉庫:

public interface BookRepositoryCustom {

    void saveAndLog(Book book);
}

這是實現:

@Repository
public class BookRepositoryCustomImpl implements BookRepositoryCustom {

    private static Logger logger = LoggerFactory.getLogger(BookRepositoryCustomImpl.class);

    @Autowired
    private EntityManager entityManager;

    @Override
    @Transactional
    public void saveAndLog(Book book) {

        logger.debug("saving the book entiry "+book.toString());
        entityManager.persist(book);
    }
}

這是我的主要方法:

public static void main(String[] args) {
    ApplicationContext context = SpringApplication.run(SpringDataTestApplication.class, args);
    BookRepository repo = context.getBean(BookRepository.class);
    Book book = new Book();
    book.setTitle("dynamic book");
    repo.saveAndLog(book);
}

一切似乎都還可以,但應用程序崩潰了,無法正常工作。 我想知道是否應該向引導彈簧介紹我的自定義存儲庫,否則它將被自動掃描。

用名稱BookRepositoryImpl而不是BookRepositoryCustomImpl編寫實現類:

    @Component
    public class BookRepositoryImpl implements BookRepositoryCustom {
    .......
    }

您也可以參考文檔:

https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.custom-implementations

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM