简体   繁体   English

自定义存储库行为Spring-Boot

[英]Customizing Repository behavior Spring-Boot

I want to add customize behavior to my repository for example I want to add a method that save and log my entity this is my repository: 我想向我的存储库添加自定义行为,例如,我想添加一种保存并记录我的实体的方法,这就是我的存储库:

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

    Book findByTitle(String bookName);

}

and this is my custom repo: 这是我的自定义仓库:

public interface BookRepositoryCustom {

    void saveAndLog(Book book);
}

and this is the implementation: 这是实现:

@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);
    }
}

and this is my main method: 这是我的主要方法:

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);
}

every thing seems to be ok but app hase crash and do not work. 一切似乎都还可以,但应用程序崩溃了,无法正常工作。 I wonder if I should tell the bootspring about my custom Repository or it will be scaned automatically. 我想知道是否应该向引导弹簧介绍我的自定义存储库,否则它将被自动扫描。

Write your implementation class with the name BookRepositoryImpl and not BookRepositoryCustomImpl : 用名称BookRepositoryImpl而不是BookRepositoryCustomImpl编写实现类:

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

You can refer the documentation also : 您也可以参考文档:

https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.custom-implementations 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