Database, JPA Queries, Cardinality Mappings Flashcards

1
Q

What does a One-to-Many (1:N) cardinality mapping signify in database relationships?

A

In a One-to-Many (1:N) cardinality mapping, a single instance of one entity is associated with multiple instances of another entity. However, each instance of the latter entity is related to only one instance of the former entity.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What does a Many-to-One (N:1) cardinality mapping represent in database relationships?

A

In a Many-to-One (N:1) cardinality mapping, multiple instances of one entity are related to a single instance of another entity.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Describe the One-to-One (1:1) cardinality mapping in database relationships.

A

One-to-One (1:1) cardinality mapping represents a direct relationship where one instance of an entity is associated with exactly one instance of another entity. Both entities have a unique connection, often reflecting specific attributes or dependencies between them.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Explain Many-to-Many (N:N) cardinality mapping in database relationships.

A

Many-to-Many (N:N) cardinality mapping signifies a complex relationship where multiple instances of one entity can be linked to multiple instances of another entity. To manage this, a junction table or intermediary entity is introduced to facilitate the connections between these entities.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What defines the Zero or One-to-Many (0/1:N) cardinality mapping in database relationships?

A

Zero or One-to-Many (0/1:N) cardinality mapping represents instances where one entity is associated with multiple instances of another entity. However, the initial entity may have either zero or one relationship with the second entity. This indicates an optional connection.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How is a Many-to-Zero or One (N:0/1) cardinality mapping characterized in database relationships?

A

Many-to-Zero or One (N:0/1) cardinality mapping represents a scenario where multiple instances of an entity have an optional association with another entity. The second entity can be linked to zero or one instance of the initial entity.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What does JPA stand for?

A

JPA stands for Java Persistence API. It’s a Java specification for managing relational data in applications using object-relational mapping (ORM) techniques.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Explain JPQL in JPA.

A

JPQL (Java Persistence Query Language) is a query language used with JPA to perform database operations. It’s similar to SQL but operates on Java objects rather than database tables. JPQL allows querying entities based on their properties and relationships.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How do you execute JPQL queries in JPA?

A

In JPA, JPQL queries can be executed using the EntityManager interface’s createQuery() method. This method accepts JPQL queries as strings and returns a Query object that can be used to execute the queries.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What are the benefits of using JPA queries?

A

JPA queries provide a standardized way to interact with databases, making applications database-independent.
They allow developers to write queries using an object-oriented approach, abstracting the underlying database structure.
JPA queries support various query types, including SELECT, UPDATE, DELETE, and INSERT operations.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Differentiate between JPQL and SQL.

A

JPQL is object-oriented and operates on entities and their attributes, focusing on Java objects. SQL, on the other hand, is a database-oriented language that deals with tables, rows, and columns directly in the database.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What does the Spring Physical Strategy refer to in Spring Data JPA?

A

The Spring Physical Strategy in Spring Data JPA deals with how Java entities are mapped to the underlying database structure, including tables, columns, constraints, and relationships.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What are the common components of the Spring Physical Strategy in Spring Data JPA?

A

Table Creation Strategy: Defines how tables are created in the database based on entity definitions.
Column Mapping: Maps Java entity attributes to database columns.
Relationship Mapping: Establishes relationships between entities and maps them to the database structure.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

How does Spring Data JPA handle table creation based on entity classes?

A

Spring Data JPA provides strategies like CREATE, CREATE_IF_NOT_EXIST, and VALIDATE to manage table creation during application startup or runtime.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What annotations are used in Spring Data JPA for mapping columns and relationships?

A

Column Mapping: @Column annotation for specifying column details.
Relationship Mapping: @OneToOne, @OneToMany, @ManyToOne, @ManyToMany for defining relationships and corresponding foreign keys.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is “Spring Open in View”?

A

Spring Open in View is a pattern that allows Hibernate Sessions (database connections) to remain open for the entire duration of processing an HTTP request. It’s often used in conjunction with web frameworks to automatically open and close sessions during request handling.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

How does Spring Open in View work in Spring Framework?

A

Spring Open in View leverages interceptors or filters to open a Hibernate Session at the beginning of a request and close it after the view has been rendered, ensuring the session remains open for the entire request cycle.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What are the advantages and disadvantages of Spring Open in View?

A

Advantages: Simplifies transaction management by allowing lazy-loading in the view layer, making it easier to work with ORM frameworks.
Disadvantages: Can cause performance issues due to longer session duration, leading to potential database connection leaks or inefficient resource usage.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Which configuration options are related to Spring Open in View?

A

OpenEntityManagerInViewFilter for JPA-based applications.
OpenSessionInViewFilter for Hibernate-based applications.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What are inheritance strategies in JPA?

A

In JPA, inheritance strategies define how entities with inheritance hierarchies are mapped to the relational database.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Name the different inheritance strategies in JPA.

A

There are three inheritance strategies in JPA: SINGLE_TABLE, TABLE_PER_CLASS, and JOINED.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Describe the SINGLE_TABLE inheritance strategy in JPA.

A

In the SINGLE_TABLE strategy, all entities in an inheritance hierarchy are mapped to a single database table, using discriminator columns to differentiate between entity types.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What does the TABLE_PER_CLASS inheritance strategy do in JPA?

A

The TABLE_PER_CLASS strategy maps each concrete entity class to its table, duplicating common fields across tables but avoiding null values.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

Explain the JOINED inheritance strategy in JPA.

A

With the JOINED strategy, each entity class in the hierarchy corresponds to a separate table in the database, linked through foreign key relationships.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

Which inheritance strategy provides normalized tables in JPA?

A

The JOINED strategy provides normalized tables as it separates entity attributes into individual tables based on the entity hierarchy.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

What factors should be considered when choosing an inheritance strategy in JPA?

A

Considerations include performance, ease of querying, maintenance, and the nature of the inheritance hierarchy when choosing an appropriate strategy.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

What is a lazy fetch type in JPA?

A

Lazy fetching delays the loading of associated data until it’s explicitly requested, enhancing performance by loading data only when needed.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

Explain the purpose of the @ManyToOne annotation in JPA.

A

@ManyToOne establishes a many-to-one relationship between entities, indicating that multiple instances of one entity can be associated with a single instance of another entity.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

What does the @Entity annotation signify in JPA?

A

The @Entity annotation marks a Java class as a persistent entity, indicating that it is mapped to a database table.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

How do you denote a primary key field in JPA?

A

In JPA, you mark a field as a primary key using the @Id annotation.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

What is the purpose of the @DiscriminatorColumn annotation in JPA?

A

@DiscriminatorColumn in JPA specifies the database column that holds the discriminator value, aiding in distinguishing between different subclasses when using inheritance strategies like SINGLE_TABLE.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

What does “Spring Boot ambiguity service” refer to, particularly concerning dependency injection?

A

In Spring Boot, “ambiguity service” denotes a scenario where multiple beans match a specific dependency or qualifier, causing ambiguity in selecting the correct bean during dependency injection, often requiring disambiguation strategies like using @Qualifier or refining bean definitions.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

What are the multiple options to consume large query results?

A

Paging, Offset-based scrolling, Keyset-based scrolling.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

How can you use named parameters in Spring Data JPA?

A

By using the @Param annotation to give a method parameter a concrete name and bind the name in the query.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

What does the #{#entityName} expression do in Spring Data JPA?

A

It dynamically inserts the entity name of the domain type associated with the repository.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

How can you activate Hibernate comments in Spring Boot?

A

By setting spring.jpa.properties.hibernate.use_sql_comments=true in the application.properties file.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

What does the @EntityGraph annotation do in Spring Data JPA?

A

It configures the fetch plan of a query by referencing a named entity graph on an entity.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

What is the purpose of scrolling in query results?

A

Scrolling allows a more fine-grained approach to iterate through larger result sets in chunks.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

How does Keyset-Filtering differ from Offset-based scrolling?

A

Keyset-Filtering leverages built-in capabilities of the database to reduce computation and I/O requirements by using a stable sorting order and passing keys into the query to resume scrolling.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
Q

What is the use of the @Modifying annotation in Spring Data JPA?

A

It triggers a query annotated to the method as an updating query instead of a selecting one.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
41
Q

How can you add custom comments into JPA operations?

A

By applying the @Meta annotation to repository operations, allowing custom comments to be inserted into queries.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
Q

What does the Window<T> in Spring Data JPA scrolling represent?</T>

A

It represents a chunk of query results that can be iterated through until the entire query result is consumed.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
43
Q

What are the three main scrolling methods used in Spring Data JPA for handling large query results?

A

The three scrolling methods in Spring Data JPA for handling large query results are Paging, Offset-based scrolling, and Keyset-based scrolling.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
44
Q

What annotation can be used in Spring Data JPA to define named parameters in query methods, solving potential issues with parameter position?

A

The @Param annotation in Spring Data JPA is used to give method parameters a concrete name and bind that name in the query.

45
Q

In Spring Data JPA, what purpose does the @Query annotation serve?

A

The @Query annotation is used to define custom queries in repository methods, either in JPQL (Java Persistence Query Language) or native SQL.

46
Q

What is the significance of the @Modifying annotation in Spring Data JPA?

A

The @Modifying annotation is used in combination with the @Query annotation to declare modifying queries, indicating that the method is an updating query instead of a selecting one.

47
Q

What is the purpose of the @EntityGraph annotation in Spring Data JPA?

A

The @EntityGraph annotation is used to configure the fetch plan of a query result by referencing a named entity graph definition or defining ad hoc entity graphs.

48
Q

What are some common strategies for query lookup in Spring Data JPA?

A

The common query lookup strategies in Spring Data JPA include Create Query, Query Creation from Method Name, @Query Annotation, Named Queries, and Custom Implementation.

49
Q

What is a JPA Named Query?

A

A JPA Named Query is a statically defined query associated with an entity using the @NamedQuery annotation or XML-based configurations, allowing queries to be referenced by their names.

50
Q

How is a Named Query defined using annotations in JPA?

A

A Named Query using annotations in JPA is defined by annotating the entity class with @NamedQuery and providing a name along with the query string, like:

@Entity
@NamedQuery(name = “Employee.findAll”, query = “SELECT e FROM Employee e”)
public class Employee {
// Entity fields and methods
}

51
Q

What are the advantages of using JPA Named Queries?

A

The advantages of using JPA Named Queries include enhanced maintainability, improved readability, and the ability to reuse queries throughout the application.

52
Q

How are Named Queries used in JPA?

A

Named Queries are used in JPA by referencing the query name defined in the @NamedQuery annotation or XML configuration using EntityManager methods like createNamedQuery() or createNamedStoredProcedureQuery().

53
Q

Can Named Queries be defined using XML configurations in JPA?

A

Yes, Named Queries can be defined using XML configurations in JPA by adding <named-query> elements within the <entity> tags in the persistence.xml file.</entity></named-query>

54
Q

How can Named Queries be parameterized in JPA?

A

Named Queries in JPA can be parameterized by using named parameters in the query string and providing corresponding parameter values when invoking the named query through EntityManager.

55
Q

How is a simple LIKE expression written in a JPA query?

A

A simple LIKE expression in a JPA query is written using the % wildcard character. For example:

@Query(“SELECT p FROM Product p WHERE p.name LIKE %:keyword%”)
List<Product> findProductsByNameContaining(@Param("keyword") String keyword);</Product>

56
Q

What additional functionality can be added to a LIKE expression in JPA queries?

A

In JPA queries, additional functionality like specifying the position of % wildcards, applying escape characters, or combining wildcards with SpEL expressions is possible for more advanced pattern matching.

57
Q

How can you perform case-insensitive searches using LIKE expressions in JPA?

A

To perform case-insensitive searches in JPA using LIKE expressions, you can use the LOWER() or UPPER() functions in combination with the % wildcard. For instance:

@Query(“SELECT u FROM User u WHERE LOWER(u.username) LIKE LOWER(concat(‘%’, :username, ‘%’))”)
List<User> findUsersByUsernameIgnoreCase(@Param("username") String username);</User>

58
Q

What are Native Queries in JPA?

A

Native Queries in JPA are SQL queries that are written in the native database query language (e.g., SQL for a specific database) and executed through the JPA EntityManager.

59
Q

How are Native Queries executed in JPA?

A

In JPA, Native Queries are executed using the createNativeQuery() method of the EntityManager. This method allows the execution of SQL queries in their native format.

60
Q

What are some advantages of using Native Queries in JPA?

A

Performance: Native Queries can sometimes offer better performance for complex or specific database operations.
Full SQL Support: Allows leveraging database-specific functionalities that might not be directly supported by JPA JPQL.

61
Q

What are the potential drawbacks of using Native Queries in JPA?

A

Database Portability: Native Queries might make the application less portable across different databases due to their specific syntax.
Loss of JPA Abstraction: Direct SQL queries bypass some of the benefits of JPA, such as object mapping.

62
Q

How do you execute a Native Query in JPA?

A

Here’s an example of executing a Native Query in JPA:

Query nativeQuery = entityManager.createNativeQuery(“SELECT * FROM users WHERE age > :age”, User.class);
nativeQuery.setParameter(“age”, 25);
List<User> users = nativeQuery.getResultList();</User>

63
Q

Can Native Queries return managed entities in JPA?

A

Yes, Native Queries in JPA can return managed entities by specifying the entity class in the createNativeQuery() method, allowing the result to be mapped to entity objects.

64
Q

How do you create a Sort instance in Spring Data JPA?

A

Sort sort = Sort.by(Sort.Direction.ASC, “propertyName”);

65
Q

Can you sort by multiple properties using Sort in Spring Data JPA?

A

Sort sort = Sort.by(Sort.Direction.ASC, “property1”).and(Sort.by(Sort.Direction.DESC, “property2”));

66
Q

How do you apply Sort to a Spring Data JPA query method?

A

List<User> findByLastName(String lastName, Sort sort);
This allows applying the specified Sort instance to the query method, sorting the result set accordingly.</User>

67
Q

Does Sort in Spring Data JPA support ignoring case when sorting?

A

Sort sort = Sort.by(Sort.Direction.ASC, “propertyName”).ignoreCase();

68
Q

How can you sort dynamically in Spring Data JPA?

A

You can create a Sort instance dynamically based on request parameters or conditions within your code and apply it to your query method.

69
Q

What are the different options available for consuming large query results in Spring Data JPA?

A

Three main options are available:

Paging.
Offset-based scrolling.
Keyset-based scrolling.

70
Q

How does offset-based scrolling differ from paging in Spring Data JPA?

A

Offset-based scrolling is a lighter variant compared to paging because it does not require the total result count, allowing direct skipping to a specific result offset without needing to fetch all preceding records.

71
Q

What is the advantage of using keyset-based scrolling over offset-based scrolling?

A

Keyset-based scrolling leverages database indexes to avoid the shortcomings of offset-based result retrieval. It aims to reduce computational and I/O requirements by using a stable sorting order and a set of keys to resume scrolling.

72
Q

How can you use scrolling with Spring Data JPA query methods?

A

Scrolling can be utilized with query methods by returning a Window<T> type that allows obtaining the scroll position to resume fetching the next window of results until the entire query result is consumed.</T>

73
Q

Could you demonstrate a code snippet for using offset-based scrolling in Spring Data JPA?

A

interface UserRepository extends Repository<User, Long> {
Window<User> findFirst10ByLastNameOrderByFirstName(String lastName, OffsetScrollPosition position);
}
This method declaration returns a Window<User> using offset-based scrolling.</User></User>

74
Q

What is the purpose of using named parameters in Spring Data JPA?

A

Named parameters provide a way to bind method parameters with concrete names in the query, enhancing readability and refactoring flexibility in query methods.

75
Q

How are named parameters used in Spring Data JPA query methods?

A

They are utilized by annotating method parameters with @Param(“parameterName”) and then referencing these names in the query using :parameterName.

76
Q

What is the significance of using @Param annotation in Spring Data JPA?

A

The @Param annotation is used to assign a concrete name to a method parameter and bind that name in the query. It aids in disambiguating parameters in complex queries.

77
Q

How can Java 8’s parameter name discovery be utilized in Spring Data JPA?

A

As of version 4, Spring fully supports Java 8’s parameter name discovery based on the -parameters compiler flag. By using this flag, the @Param annotation for named parameters can be omitted.

78
Q

Can you provide an example of using named parameters in Spring Data JPA query methods?

A

public interface UserRepository extends JpaRepository<User, Long> {

@Query(“select u from User u where u.firstName = :firstName and u.lastName = :lastName”)
User findByFirstNameAndLastName(@Param(“firstName”) String firstName, @Param(“lastName”) String lastName);
}
This example demonstrates the usage of named parameters (:firstName and :lastName) in a query method.

79
Q

What is the role of SpEL expressions in Spring Data JPA?

A

SpEL (Spring Expression Language) expressions in Spring Data JPA allow dynamic expression evaluation within query annotations, enabling more flexible and dynamic query constructions.

80
Q

In Spring Data JPA, what is the purpose of #{#entityName} in a query method?

A

{#entityName} dynamically resolves to the entity name associated with the repository. It allows query methods to refer to the entity name in a manner independent of potential future entity name changes.

81
Q

How does SpEL handle the #{#entityName} expression in repository query methods?

A

{#entityName} dynamically injects the entity name into the query. If an entity has set the name property in the @Entity annotation, that name is used. Otherwise, it defaults to the simple class name of the domain type.

82
Q

Can you provide an example of using SpEL expressions in a Spring Data JPA query method?

A

public interface UserRepository extends JpaRepository<User, Long> {

@Query(“select u from #{#entityName} u where u.lastName = ?1”)
List<User> findByLastName(String lastName);
}
In this example, #{#entityName} refers to the entity name, allowing the query to be more flexible in case the entity name changes.</User>

83
Q

What does the escape(String) method in SpEL context do in repository query methods?

A

The escape(String) method sanitizes input values, specifically escaping wildcards like _ and % in values, preventing unwanted data retrieval from like-conditions.

84
Q

What does the @Modifying annotation do in Spring Data JPA?

A

The @Modifying annotation marks a query method as modifying. It signifies that the annotated query is an update or delete operation, distinguishing it from a selecting query.

85
Q

When using the @Modifying annotation in Spring Data JPA, what consideration should be made regarding EntityManager’s state?

A

Upon executing a modifying query, the EntityManager might retain outdated entities. By default, it doesn’t automatically clear the EntityManager to avoid dropping non-flushed changes. However, this can be configured by setting the clearAutomatically attribute of @Modifying to true.

86
Q

Is the @Modifying annotation mandatory for custom query methods in Spring Data JPA?

A

No, the @Modifying annotation is only necessary for query methods explicitly annotated with @Query. Derived query methods or custom methods, not annotated with @Query, do not require this annotation.

87
Q

What’s the role of @Query in modifying queries in Spring Data JPA?

A

The @Query annotation helps define custom query methods that execute modifying operations such as updates or deletes in Spring Data JPA.

88
Q

How does Spring Data JPA support derived delete queries?

A

Spring Data JPA supports derived delete queries, allowing developers to avoid explicitly declaring JPQL queries. For instance:

interface UserRepository extends Repository<User, Long> {
void deleteByRoleId(long roleId);
}
In this example, the method deleteByRoleId() generates a delete query based on the method name.

89
Q

What is scrolling in the context of Spring Data JPA?

A

Scrolling refers to a technique for processing large query results efficiently without loading the entire dataset into memory. It allows the retrieval of results in manageable chunks or windows.

90
Q

What are the different methods available for consuming large query results in Spring Data JPA?

A

The methods available for consuming large query results are:

Paging
Offset-based scrolling
Keyset-based scrolling

91
Q

How does offset-based scrolling work in Spring Data JPA?

A

Offset-based scrolling skips a defined number of results before retrieving a chunk of data. It is similar to pagination but does not require the total result count. However, it might still require materializing the full query result before returning the relevant chunk.

92
Q

What is keyset-based scrolling in Spring Data JPA?

A

Keyset-based scrolling, also known as keyset pagination, leverages database indexes to retrieve subsequent chunks of data. It uses a stable sorting order and a set of keys from the last entity fetched to resume fetching from that position. This approach aims to reduce computation and I/O requirements for individual queries.

93
Q

In Spring Data JPA, how can you retrieve query results using scrolling?

A

Spring Data JPA offers methods like findFirst10By…() that can be combined with scroll positions like OffsetScrollPosition or KeysetScrollPosition to retrieve and navigate through query results using scrolling techniques.

94
Q

What are Fetch- and LoadGraphs in the context of Spring Data JPA?

A

Fetch- and LoadGraphs in Spring Data JPA allow the specification of the fetch plan for entity queries. They help define how related entities should be loaded or fetched along with the primary entity.

95
Q

How are Fetch- and LoadGraphs configured in Spring Data JPA entities?

A

In Spring Data JPA entities, Fetch- and LoadGraphs are configured using the @NamedEntityGraph annotation. This annotation references a named entity graph definition that specifies how related entities should be loaded.

96
Q

What is the purpose of the @NamedEntityGraph annotation in Spring Data JPA entities?

A

The @NamedEntityGraph annotation allows the definition of a named entity graph on an entity. It specifies the attribute nodes (related entities) that need to be fetched along with the primary entity.

97
Q

How can you reference a named entity graph in a Spring Data JPA repository query method?

A

In a Spring Data JPA repository query method, you can reference a named entity graph using the @EntityGraph annotation. This annotation is applied to the query method and specifies the named entity graph (value) and the type of fetching (type).

98
Q

Besides named entity graphs, what other way can you define ad hoc entity graphs in Spring Data JPA repository query methods?

A

You can define ad hoc entity graphs in Spring Data JPA repository query methods using the @EntityGraph annotation directly within the query method. This annotation specifies the attribute paths (related entities) to be fetched without needing an explicitly named entity graph.

99
Q

What are query hints in Spring Data JPA?

A

Query hints in Spring Data JPA are additional instructions or directives provided to the underlying database to optimize query execution or alter the behavior of query execution plans.

100
Q

How are query hints applied to queries in Spring Data JPA?

A

In Spring Data JPA, query hints are applied using the @QueryHints annotation. This annotation is placed on the repository query method and takes JPA @QueryHint annotations as values to specify the hints.

101
Q

What parameters does the @QueryHints annotation take?

A

The @QueryHints annotation in Spring Data JPA takes two parameters:

value: An array of JPA @QueryHint annotations specifying the hints to be applied.
forCounting: A boolean flag to potentially disable hints for the count query triggered during pagination.

102
Q

How can you disable query hints for the count query triggered during pagination in Spring Data JPA?

A

To potentially disable hints for the count query triggered during pagination in Spring Data JPA, set the forCounting parameter of the @QueryHints annotation to false.

103
Q

What’s the purpose of using query hints in Spring Data JPA?

A

Query hints in Spring Data JPA serve to influence the execution plans of database queries, potentially optimizing performance, altering caching behavior, or guiding the query planner in selecting better query execution strategies.

104
Q

What is the EntityManager in JPA?

A

The EntityManager is the primary interface through which applications interact with the persistence context in JPA. It manages the lifecycle of entities, provides methods for querying the database, and persists changes to entities.

105
Q

What are the main responsibilities of the EntityManager?

A

The EntityManager in JPA is responsible for:

Managing entity lifecycle (persisting, merging, removing, and refreshing entities)
Executing queries against the database
Maintaining the persistence context

106
Q

How is the EntityManager obtained in JPA?

A

In JPA, the EntityManager is typically obtained using the EntityManagerFactory. An instance of the EntityManager is acquired by calling the createEntityManager() method on the EntityManagerFactory.

107
Q

What is the purpose of the persistence context in JPA EntityManager?

A

The persistence context in the EntityManager is a collection of entity instances that are currently being managed. It tracks changes to these entities and synchronizes them with the underlying database during specific points, like transaction commits.

108
Q

How does EntityManager interact with entities?

A

EntityManager interacts with entities using various methods:

persist(Object entity): Adds a new entity to the persistence context.
merge(Object entity): Updates the state of a detached entity.
remove(Object entity): Marks an entity for removal from the persistence context.
find(Class<T> entityClass, Object primaryKey): Retrieves an entity by its primary key.
createQuery(String jpql): Creates a query to retrieve entities based on JPQL.</T>