Missing CrudRepository#findOne method

后端 未结 5 977
我在风中等你
我在风中等你 2020-12-02 07:00

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 t

相关标签:
5条回答
  • 2020-12-02 07:34

    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(…)         ║
    ╚═════════════════════╩═══════════════════════╝
    
    0 讨论(0)
  • 2020-12-02 07:39

    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);
    
    0 讨论(0)
  • 2020-12-02 07:45

    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); 
        } 
    } 
    
    0 讨论(0)
  • 2020-12-02 07:50

    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);
    
    0 讨论(0)
  • 2020-12-02 07:54

    A pragmatic transform

    Old way:

    Entity aThing = repository.findOne(1L);
    

    New way:

    Optional<Entity> aThing = repository.findById(1L);
    
    0 讨论(0)
提交回复
热议问题