Missing CrudRepository#findOne method

62,047

Solution 1

Please see DATACMNS-944 which is associated to this commit which has the following renames

╔═════════════════════╦═══════════════════════╗
║      Old name       ║       New name        ║
╠═════════════════════╬═══════════════════════╣
║ findOne(…)          ║ findById(…)           ║
╠═════════════════════╬═══════════════════════╣
║ save(Iterable)      ║ saveAll(Iterable)     ║
╠═════════════════════╬═══════════════════════╣
║ findAll(Iterable)   ║ findAllById(…)        ║
╠═════════════════════╬═══════════════════════╣
║ delete(ID)          ║ deleteById(ID)        ║
╠═════════════════════╬═══════════════════════╣
║ delete(Iterable)    ║ deleteAll(Iterable)   ║
╠═════════════════════╬═══════════════════════╣
║ exists()            ║ existsById(…)         ║
╚═════════════════════╩═══════════════════════╝

Solution 2

Note that findById is not an exact replacement for findOne, it returns an Optional instead of null.

Being not very familiar with new java things it took me a little while to figure out, but this turns the findById behavior into the findOne one:

return rep.findById(id).orElse(null);

Solution 3

We had many hundreds of usages of the old findOne() method. Rather than embark on a mammoth refactor, we ended up creating the following intermediary interface and had our repositories extend it instead of extending JpaRepository directly

@NoRepositoryBean
public interface BaseJpaRepository<T, ID> extends JpaRepository<T, ID> { 
    default T findOne(ID id) { 
        return (T) findById(id).orElse(null); 
    } 
} 

Solution 4

A pragmatic transform

Old way:

Entity aThing = repository.findOne(1L);

New way:

Optional<Entity> aThing = repository.findById(1L);

Solution 5

An other way more. Add a @Query. Even if I would prefer to consume the Optional:

@Repository
public interface AccountRepository extends JpaRepository<AccountEntity, Long> {

    @Query("SELECT a FROM AccountEntity a WHERE a.id =? 1")
    public AccountEntity findOne(Long id);

}
Share:
62,047

Related videos on Youtube

Andrii Abramov
Author by

Andrii Abramov

Engineers like to solve problems. If there are no problems handily available, they will create their own problems. (c) The Boy Scouts have a rule: "Always leave the campground cleaner than you found it." If you find a mess on the ground, you clean it up regardless of who might have made the mess. You intentionally improve the environment for the next group of campers. Actually the original form of that rule, written by Robert Stephenson Smyth Baden-Powell, the father of scouting, was "Try and leave this world a little better than you found it." My LinkedIn

Updated on October 13, 2021

Comments

  • Andrii Abramov
    Andrii Abramov over 2 years

    I am using Spring 5 in my project. Until today there was available method CrudRepository#findOne.

    But after downloading latest snapshot it suddenly disappeared! Is there any reference that the method is not available now?

    My dependency list:

    apply plugin: 'java'
    apply plugin: 'org.springframework.boot'
    apply plugin: 'io.spring.dependency-management'
    
    
    repositories {
        mavenCentral()
        maven { url "https://repo.spring.io/snapshot" }
        maven { url "https://repo.spring.io/milestone" }
    }    
    
    dependencies {
        compile 'org.springframework.boot:spring-boot-starter-data-jpa'
    
        runtime 'com.h2database:h2:1.4.194'
    }
    

    UPDATE:

    Seems that this method has been replaced with CrudRepository#findById

  • GabiM
    GabiM almost 6 years
    Not the best idea: your code will continue working but you're not using the API as you should. Optional was added to clean the code from all the null checks. Just change the return type of you method and use Optional like a good boy-scout should
  • zeusalmighty
    zeusalmighty almost 6 years
    @GabiM This would be great if you have control of all the methods downstream. Even if you do have control of everything downstream and your project is not a dependency for some other third party project, if the methods downstream code for null (as in, create if not exists, or do some logic if missing), then you have to fix them as well.
  • Christian
    Christian almost 6 years
    Is there a migration guide I missed, or is this vague line from the release notes all in terms of announcements there was? "DATAJPA-1104 - Adapt to API changes in repository interfaces" How did you find out? :-)
  • Sean Carroll
    Sean Carroll almost 6 years
    Not sure if this is any migration guide but you can find reference to it in the Kay release train wiki (github.com/spring-projects/spring-data-commons/wiki/…) as well as the Spring Data Commons changelog (docs.spring.io/spring-data/commons/docs/current/changelog.t‌​xt)
  • Ken007
    Ken007 over 4 years
    Top solution for me. No need for casting. return findById(id).orElse(null); suffices
  • Scott Carlson
    Scott Carlson about 4 years
    In reference to the link from @GabiM, I just wanted to point out that even that link says "It is important to note that the intention of the Optional class is not to replace every single null reference"
  • Scott Carlson
    Scott Carlson almost 4 years
    Totally agree. Saved me hundreds of lines of changes.