Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

406
Views
Spring Data JPA repository methods overloading

For example, I have a book JpaRepository. Book has a field called Name, the book repository has a method findOneByName (as the jpa repository method naming convention). But I need two different versions of findOneByName to use in different use cases. One version is lock annotated, the other is lock-free. Like this:

public interface BookRepository extends JpaRepository<BookDAO, Long> {

   @Lock(LockModeType.READ)
   BookDAO findOneByName( String name );

   BookDAO findOneByName( String name );
}

Is it possible to achieve this in Spring? If so, how to distinguish the two methods when calling them. If not, is there another way to do it while still using the Spring JPA repository interfaces (like findOneBy***).

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

According to reference we can name query methods with these prefixes: find…By, read…By, query…By, count…By, and get…By.

So methods BookDAO findByName(String name) and BookDAO getByName(String name) will do the same thing.

about 4 years ago · Santiago Trujillo Report

0

I dont know if it can be done your way. But i would create different methods

 public interface BookRepository extends JpaRepository<BookDAO, Long> {

   @Lock(LockModeType.READ)
   @Query("select b from Book b where b.name = :name")
   BookDAO findOneByNameForRead( String name );

   BookDAO findOneByName( String name );

}

or you can create methods in your service layer instead of using spring jparepository to handle locking. and use it across where it is needed to be updated, and all read methods marked as @Transactional(readOnly = true)

@PersistenceContext
private EntityManager em;
...

public  Book findOneBookForUpdate(String id) {

    Book book = em.find(Book.class, id);
    if (book != null) {
        em.lock(book, LockModeType.PESSIMISTIC_WRITE);
    }

    return book;
}
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!