ThinkGeek
ThinkGeek

Reputation: 5157

Spring JPA selecting from where clause

I am using Spring JPA to perform all database operations. However I don't know how to select specific rows (connected by simple WHERE clause) from a table in Spring JPA?

For example:

SELECT * FROM user where name=agrawalo AND [email protected] 

User Class:

@Entity
Class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long userId;

    @Column(nullable = false)
    private String name;

    @Column(nullable = false)
    private String email;

   // Getters and Setters
}

Repository:

public interface UserRepository extends JpaRepository<User, Integer> {

}

Upvotes: 9

Views: 33637

Answers (4)

Syed Noman Ahmed
Syed Noman Ahmed

Reputation: 103

I know I am very very late to this but I still want to provide another solution that one would like to use. This is particularly useful when you think the queries generated by method names do not serve the purpose that you want and you really want to write the native queries. To do that, you can actually use the @Query annotation in your repository and put your query inside it like below:

@Query(value = "SELECT * FROM user where name = ?1 AND email = ?2", nativeQuery = true)
List<User> getUserByNameAndEmail(String name, String email);

Here the @Query tells that the query provided in the value attribute needs to be executed and the nativeQuery attribute tells that it is a native sql query.

Notice that values for name and email are provided as ?1 and ?2 respectively which means these are placeholders and will be replaced by the parameters that getUserByNameAndEmail repository method will receive at runtime in variables name and email.

Upvotes: 5

Sree
Sree

Reputation: 374

Simply you can declare below method in you repository interface, implementation will be taken care by Spring-data-jpa

User findByNameAndEmail(String name, String email);

Upvotes: 2

Antoniossss
Antoniossss

Reputation: 32535

public interface UserRepository extends JpaRepository<User, Integer> {
     public User findUserByNameAndEmail(String name,String email);
}

Implementation will be created on the fly.

Upvotes: 3

pvpkiran
pvpkiran

Reputation: 27078

You don't need to write queries for such simple things if you are using spring-data-jpa. you can write a method name and spring-data will formulate a query based on your method name and get the results.

public interface UserRepository extends JpaRepository<User, Integer> {
  Optional<User> findByNameAndEmail(String name, String email)
}

Create a method like above and call the method with the required arguments.
If you don't want(not advisable) to use Optional, you can just use User as return type. In such case, if there are no entries matching your arguments then you would have null returned.

Upvotes: 13

Related Questions