DEV Community

Swapnil Gupta
Swapnil Gupta

Posted on

SQL Query in Spring Boot

we will understand the usages by examples like one in the case of finding existing record through the object and other in the case of searching through api call

To find someone by email or record that is already exist in database records

public interface UserRepository extends JpaRepository<User,Integer>{
    Optional<User> findByUsername(String username);
    // Optional<User> findByEmail(String email);

    @Query("SELECT u.username, FROM User u WHERE = :email")
    Optional<User> findByEmail(@Param("email") String email);

Enter fullscreen mode Exit fullscreen mode

To search a query

@Query("SELECT p FROM Product p WHERE " +
            " LIKE CONCAT('%',:query, '%')")
    List<Product> searchProducts(String query);
Enter fullscreen mode Exit fullscreen mode

@Query tag is used in both the cases we will look for the differences in controller class

    public ResponseEntity<String> createUser(@RequestBody User user) {          if(userService.isUserExists(user.getUsername(), user.getEmail())) {
            System.out.println("User exist already");
            return ResponseEntity.status(HttpStatus.CONFLICT).body("Username or Email already exists for : " + user.getEmail());

          User createdUser = userService.createUser(user);
          System.out.println("new user created");
          return ResponseEntity.ok("User created successfully");
Enter fullscreen mode Exit fullscreen mode

@RequestBody is used to accept the body of user

if in case of Product search

    public ResponseEntity<List<Product>> searchProducts(@RequestParam("query") String query){
        return ResponseEntity.ok(service.searchProducts(query));
Enter fullscreen mode Exit fullscreen mode

@RequestParam is there, which can accept parameters and optional .

I want to keep it short and simple, will share more connect me on

Top comments (0)