Vipul
Vipul

Reputation: 610

Find by id=1 spring data jpa

I have a table component and entity Component. I want to select id = 1 record from jpa query. Can I write 'findByIdOne' or 'findByIdEqualtoOne'? will that give me id = 1 record? Please let me know, Thanks.

Upvotes: 0

Views: 1283

Answers (4)

Brother
Brother

Reputation: 2210

Direct writing the query dsl you cant, but there is a 'way' with Java 8 using default methods:

Let's say you have the query:

public interface ComponentRespository extends CrudRepository<Component, Long> {

    @Query("select c from Component c where c.id=:id")
    Component findById(@Param("id") Long id);

    default Component findByIdOne() {
        return findById(1L);
    }
    //eventually
    default Component findByIdTwo() {
        return findById(2L);
    }
}

This way you can use:

private ComponentRespository componentRepository;

.....
Component componentOne = componentRepository.findByIdOne(); 
Component componentTwo = componentRepository.findByIdTwo(); 

Upvotes: 0

TigerT
TigerT

Reputation: 52

You can use Optional<EntityName> findById(long id) or List<EntityName> findAllById if it's not unique. We have several options: findByIdIs(long id) or findByIdEquals(long id)

Upvotes: 0

Gimby
Gimby

Reputation: 5284

No, you cannot. Refer to the Spring Data JPA documentation which documents the exact keywords that you can use.

You are free to specify the query that you want a method to execute though. Something like

@Query("select c from Component c where c.id=1")
Component findByIdOne();

I do have to put a disclaimer: by providing this solution I assume that you are really sure that ID 1 is always going to exist and will always point to exactly the same Component record in any environment that you may be running the application against. Hardcoded database IDs in your application code is not something I would ever recommend.

Upvotes: 1

TigerT
TigerT

Reputation: 52

You can use Optional<EntityName> findById(long id) or List<EntityName> findById(long id) if it's not unique.

Upvotes: 0

Related Questions