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.
List<User> findByName(@Param("name") String name);
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> {
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.