Delumees
Delumees

Reputation: 35

Spring data repository findById vs derived findBy[id-column-name]

Let's say we have an entity class with the following id:

@Entity
class SomeEntity {
    @Id
    private String key;
    ...
}

Is there any difference between using CrudRepository's findById(key) and using our own method findByKey(String key)?
And is there any difference between both when the primary key is composite, e.g:

class CompositeKey implements Serializable {
    private Integer firstKey;
    private String secondKey;
    ...
}

@Entity
@IdClass(CompositeKey.class)
class SomeEntity {
    @Id
    private Integer firstKey;
    @Id
    private String secondKey;
    ...
}

and then findById(new CompositeKey(...)) vs
findByFirstKeyAndSecondKey(int firstKey, String secondKey) ?

Upvotes: 0

Views: 966

Answers (1)

Jens Schauder
Jens Schauder

Reputation: 81882

Yes there is a difference. findById is implemented by using a dedicated method on the EntityManager which will check the 1st level cache first and therefore potentially avoids any database access.

The derived query method will create a query and execute it as long as you don't have a query cache configured.

If the entity in question isn't in the 1st level cache the code path executed is still significantly different, but it is unlikely that you'll notice it in production.

Upvotes: 1

Related Questions