Sunday, September 15, 2024

Spring JPA interview questions

 

How can you create custom queries in Spring Data JPA?

 Custom queries can be created using:

1.     Query Methods: You can define query methods directly in your repository interface. Spring Data JPA automatically generates the queries based on the method names.

public interface UserRepository extends JpaRepository<User, Long> {

    List<User> findByName(String name);

    List<User> findByEmailContaining(String emailFragment);

}

 

 

 

2.     Query Annotation

Use the @Query annotation to define custom JPQL (Java Persistence Query Language) or SQL queries.

 public interface UserRepository extends JpaRepository<User, Long> {

     @Query("SELECT u FROM User u WHERE u.name = :name")

    List<User> findByName(@Param("name") String name);

     @Query(value = "SELECT * FROM users WHERE email = :email", nativeQuery = true)

    User findByEmail(@Param("email") String email);

}

 

3.     JPQL (Java Persistence Query Language): Use @Query annotation with JPQL for complex queries.


4.     Named Queries

Named queries are predefined JPQL queries that you define using @NamedQuery or @NamedQueries in your entity class.

@Entity

@NamedQuery(name = "User.findByEmail", query = "SELECT u FROM User u WHERE u.email = :email")

public class User {

 

    @Id

    private Long id;

    private String name;

    private String email;

 

    // Getters and setters

}

 

public interface UserRepository extends JpaRepository<User, Long> {

     @Query(name = "User.findByEmail")

    User findByEmail(@Param("email") String email);

}

  

What are the different fetching strategies in JPA?

The fetching strategies are:

EAGER: The related entities are fetched immediately with the parent entity.

LAZY: The related entities are fetched only when accessed, i.e., on demand.

 

 

 

How to handle exceptions in Spring boot?

 1. Controller Advice with @ExceptionHandler

Using @ControllerAdvice in combination with @ExceptionHandler allows you to handle exceptions globally across your application or for specific controllers.

 

@ControllerAdvice

public class GlobalExceptionHandler {

 

    @ExceptionHandler(ResourceNotFoundException.class)

    @ResponseStatus(HttpStatus.NOT_FOUND)

    public ResponseEntity<String> handleResourceNotFound(ResourceNotFoundException ex) {

        return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);

    }

 

    @ExceptionHandler(Exception.class)

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)

    public ResponseEntity<String> handleGeneralException(Exception ex) {

        return new ResponseEntity<>(ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);

    }

}

 @ControllerAdvice: Designates the class as a global exception handler.

@ExceptionHandler: Specifies the type of exception to handle.

@ResponseStatus: Sets the HTTP status code.

how to close database connections/file connections with out using close() method in java

 

1. Try-With-Resources Statement

The try-with-resources statement, introduced in Java 7, is the preferred method to ensure that resources are closed automatically. Classes that implement the AutoCloseable interface (which includes Connection, Statement, ResultSet, FileInputStream, etc.) can be used with this statement.

try (Connection connection = DriverManager.getConnection(url, user, password);

     Statement statement = connection.createStatement();

     ResultSet resultSet = statement.executeQuery(query)) {

   

    // Use the connection, statement, and resultSet

 

} catch (SQLException e) {

    e.printStackTrace();

}

 

In this example, the Connection, Statement, and ResultSet are automatically closed at the end of the try block.