简体   繁体   中英

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=abc@example.com 

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> {

}

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.

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

Implementation will be created on the fly.

只需在存储库接口中声明以下方法,Spring-data-jpa 将负责实现

User findByNameAndEmail(String name, String email);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM