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

UserRepository.java

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


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

}
Enter fullscreen mode Exit fullscreen mode

To search a query

ProductRepository.java

@Query("SELECT p FROM Product p WHERE " +
            "p.name 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

 @PostMapping("adduser")
    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

  @GetMapping("/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 https://linkedin.com/in/swapnilxi

Top comments (0)