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

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay