Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

}
like image 339
Lokesh Agrawal Avatar asked May 28 '18 11:05

Lokesh Agrawal


People also ask

How do you write a JPA query for in clause?

Let's follow the Spring Data JPA naming convention to write a query method for the IN clause for the Product entity class. Example: Consider the Product entity class and if we want to retrieve products with In clause then here is the Spring data JPA query method: List<Product> findByNameIn(List<String> names);

What is @query in spring boot?

Spring Data JPA @Query The @Query annotation declares finder queries directly on repository methods. While similar @NamedQuery is used on domain classes, Spring Data JPA @Query annotation is used on Repository interface. This frees the domain classes from persistence specific information, which is a good thing.

What is the difference between JpaRepository and CrudRepository?

CrudRepository provides CRUD functions. PagingAndSortingRepository provides methods to do pagination and sort records. JpaRepository provides JPA related methods such as flushing the persistence context and delete records in a batch.


1 Answers

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.

like image 98
pvpkiran Avatar answered Oct 13 '22 09:10

pvpkiran