简体   繁体   中英

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 :

    @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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM