The execution speed of Spring Data Jpa findOne () is much slower than that of findById ().

I wrote two entity classes, A, B, where An and B have an one-to-many relationship, and classes An and C also have primary foreign key associations. The following
class A:

@Entity
public class A implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GenericGenerator(name = "idGenerator", strategy = "uuid")
    @GeneratedValue(generator = "idGenerator")
    private String id;

    @Column(nullable = false)
    @NotBlank
    private String name;
    
    @ManyToOne
    @JoinColumn(name = "cId", referencedColumnName="id")
    private C c;
}
    

Class B:

@Entity
public class B implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GenericGenerator(name = "idGenerator", strategy = "uuid")
    @GeneratedValue(generator = "idGenerator")
    private String id;

    @Column(nullable = false)
    @NotBlank
    private String name;
    
    @ManyToOne
    @JoinColumn(name = "aId", referencedColumnName="id")
    private A a;
}
    
BRepository.findOne(id) 6sBRepository.findFirstById(id) 100ms
ARepository.findOne(id)300msBBAACBfindOnefindBy 
Mar.28,2021

Hello, there is a comparative description of them in some historical information
the difference between getOne () and findOne () in Spring Data JPA
from renamed findOne () to findById ():

Optional<T> findById(ID id); 

you can get the materialized object through findById (id). Get ().

typically, when you press ID to find an entity, if the entity is not retrieved, you will return the entity or perform specific processing.

here are two classic use cases.

1) assume that if the entity cannot be found, an exception is thrown, otherwise it is returned.

you can write:

return repository.findById(id)
        .orElseThrow(() -> new NotFoundEntity(id));

2) suppose you want to apply different handling depending on whether the entity is found (there is no need to throw an exception).

you can write:

Optional<Foo> fooOptional = fooRepository.findById(id);
if (fooOptional.isPresent()){
    Foo foo = fooOptional.get();
   // processing with foo ...
}
else{
   // alternative processing....
}
Menu