Spring Interview Module 3 Data Access Flashcards

1
Q

What is checked exceptions?

A

Checked exception – Exception that is extending java.lang.Exception (except java.lang.RuntimeException) class that has to be explicitly declared in throws part of method signature of method that is throwing an exception and has to be explicitly handled by code that invokes the method.

If code that is calling the method with checked exception does not handle exception, it has to declare it in throws part of method signature.

Pros:
 Developer using API always has a list of exceptional situations that has to be handled
 Fast compile-time feedback on check if all exceptional situations were handled

Cons:
 May result in cluttered code
 Coupling between callee and caller

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

what is unchecked exceptions and why Spring prefers unchecked exceptions?

A

Unchecked exception – Exception that is extending
java.lang.RuntimeException class, does not have to be explicitly declared in throws part of method signature of method that is throwing an exception and does not have to be explicitly handled by code that invokes the method. Developer has freedom of choice if error handling should be implemented or not.

Pros:
 Reduces cluttered code
 Reduces coupling between callee and caller
Spring prefers loose coupling

Cons:
 May result in missing situations in which error handling should be implemented
 Lack of compile-time feedback on error handling

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

What is the data access exception hierarchy?

A

 Data Access Exception is a Runtime Exception

Examples of concrete Data Access Exceptions
 CannotAcquireLockException
 CannotCreateRecordException
 DataIntegrityViolationException

Purpose of this hierarchy is to create
abstraction layer on top of Data Access APIs to avoid coupling with concrete implementation of Data Access APIs. if use checked exception, APIs need to handle explicit exceptions based on different implementations

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

what is a data source in java?

A

Data Source is represented by generic interface javax.sql.DataSource which represent any data source for sql database.

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

how to configure data source in spring?

A

To configure data source in Spring you need to create a @Configuration class that will return javax.sql.DataSource bean.

You can use for example following types of javax.sql.DataSource:
 DriverManagerDataSource – basic JDBC driver connection source
 BasicDataSource – Apache DBCP for Connection Pooling
 ComboPooledDataSource - C3P0 for Connection Pool
 SmartDataSource
 AbstractDataSource
 SingleConnectionDataSource
 TransactionAwareDataSourceProxy
 DataSourceTransactionManager

Configuration of Data Source in Spring is dependent on type of application that is executed.

Type of execution:
 Standalone – Data Source is configured in @Configuration class and is created as a bean of one of supported data source types
 Spring Boot – Data Source is configured through application.properties
 Application Server – Data Source should be fetched from JNDI via
JndiDataSourceLookup / JndiTemplate, application server is
responsible for creating and managing data source requested in resources configurations of deployment descriptors

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

Which bean is very useful for development/test databases?

A

When working with development/test databases, following beans are very useful:
 EmbeddedDatabaseBuilder – allows to easily configure H2/HSQLDB embedded database with schema/data initialization scripts
 DataSourceInitializer / ResourceDatabasePopulator – allows to use
schema/data initialization scripts without usage of EmbeddedDatabaseBuilder. can be used in combination with spring data source configuration bean which set up url.

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

What is the Template design pattern?

A

Template design pattern is a behavioral design pattern that can be used to encapsulate algorithm/main flow with it steps in a way to achieve steps customization and shared code reusability.

It is achieved by creating abstract class that contains algorithm definition/main flow with shared code, and child classes extending abstract class which are customizing step or steps of the algorithm.

Template design pattern can be used to achieve greater code reusability, however since it is using inheritance, which is very strong relationship between classes it can limit future flexibility of the system. You should use this pattern with caution and you should analyze if strategy design pattern will not give you similar results. Strategy uses composition instead of inheritance and in some
cases instead of using template method, strategy can be used to achieve code reusability and also code flexibility.

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

what is the JDBC template?

A

Jdbc Template is a class located in org.springframework.jdbc.core package.
Goal of this class is to simplify use of JDBC by providing implementation of JDBC workflow, leaving application to provide SQL statements and results extractions.

Jdbc Template executes SQL queries or updates, initiates iteration over ResultSet, ResultSet mapping, also it catches exceptions and translates them into generic exceptions.

Code that interacts with Jdbc Template needs to provide implementation of callback interfaces which allows specific steps of JDBC workflow customization:
 PreparedStatementCreator
 ResultSetExtractor
 PreparedStatementSetter
 RowMapper

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

What is a callback?

A

A callback is a code or reference to the code that can be passed as an argument to the method. This method will execute passed callback during execution.

On Java level callback can be:
 Class that implements interface
 Anonymous class e.g. directly define an interface implementation inline
 Lambda expression – JDK 8
 Reference Method – JDK 8 e.g. Object :: objectMethodName

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

What are the three JdbcTemplate callback interfaces that can be used with queries (result set)?

A

Jdbc Template Callbacks that can be used with queries:
 RowMapper – interface for processing ResultSet data on per-row basis, implementation should call ResultSet.get*(..) methods, but should not call ResultSet.next(), it should only extract values from current row and based on those values should create object, which will be returned from mapRow method, implementation is usually stateless

 RowCallbackHandler – interface for processing ResultSet data on a per-row basis, implementation should call ResultSet.get*(..) methods, but should not call ResultSet.next(), it should only extract values from current row, implementation is usually stateful, it keeps accumulated data in some object, processRow method from this class does not return any value, instead method saves results into for example object field that will keep state
not recommended as stateful method makes maintenance harder.

 ResultSetExtractor – interface for processing entire ResultSet data, all rows needs to be processed and implementation should call ResultSet.next() method to move between rows, implementation is usually stateless, implementation should not close ResultSet, it will be closed by Jdbc Template

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

what are jdbc template callback methods for statements?

A

Jdbc Template other Callbacks:
 PreparedStatementCreator – should create PreparedStatement based on Connection provided by JdbcTemplate, implementation should provide SQL and parameters

 PreparedStatementSetter – should set values on PreparedStatement provided by JdbcTemplate, implementation should only set parameters, SQL will be set by JdbcTemplate

 CallableStatementCreator – should create CallableStatement based on Connection provided by JdbcTemplate, implementation should provide SQL and parameters

 PreparedStatementCallback – used internally by JdbcTemplate –
generic interface allowing number of operations on single PreparedStatement

 CallableStatementCallback – used internally by JdbcTemplate –
generic interface allowing number of operations on single CallableStatement

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

Can you execute a plain SQL statement with
the JDBC template?

A

Yes, JDBC Template allows execution of plain SQL statements with following
methods:
 query
 queryForList
 queryForObject
 queryForMap
 queryForRowSet
 execute
 update
 batchUpdate

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

When does the JDBC template acquire (and release) a connection, for every method called or once per template? Why?

A

Connection lifecycle in JDBC Template depends on transactions being involved or not.

If JDBC Template is used without transaction, then connection is acquired and released for every method call. Reason for this strategy, is to minimize amount of time when resource (connection) has to be held.

If JDBC Template is used together with transaction, then DataSourceUtils which is using TransactionSynchronizationManager will reuse connection between method calls as long as transaction is not committed or rolled back. Reason for this strategy is that connection cannot be closed when transaction is in progress, since
closing connection would also rollback any changes made.

JDBC Template uses getConnection() method from DataSource class through DataSourceUtils class. If DataSource is plain JDBC Connection source, then connection is actually opened/closed, however if Connection Pool, like DBCP or C3P0 is used, then connection is not being opened/closed, however it is acquired or
released from/to the pool.

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

How does the JdbcTemplate support generic queries? How does it return objects and lists/maps of objects?

A

Jdbc Template supports generic queries with following methods:
 queryForObject – returns single object, expects query to return only one record, if this requirement is not matched IncorrectResultSizeDataAccessException will be thrown
 queryForList – returns list of objects of declared type, expects query to return results with only one column, otherwise IncorrectResultSetColumnCountException will be thrown
 queryForMap – returns map for single row with keys representing column names and values representing database record value, expects query to return only one record, if this requirement is not matched IncorrectResultSizeDataAccessException will be thrown
 queryForRowSet – returns SqlRowSet object that contains metadata information (like column names) and allows to read results data and iterate through records All of the methods above have many versions, allowing you to specify not only query itself, but also parameters to the query and customer row mapper if required.

Jdbc Template returns objects, lists/map by using following:
 objects – queryForObject – SingleColumnRowMapper for generic types and RowMapper for custom types
 lists – queryForList – SingleColumnRowMapper for generic types
 maps – queryForMap – ColumnMapRowMapper for any query

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

Is a transaction a cross cutting concern? How is it implemented by Spring?

A

Transaction is a cross cutting concern and in Spring it is implemented with usage of @Transactional annotation.

If @Transactional annotation is present on top of the method or entire class, then each call to the method in the class will be proxied by TransactionInterceptor and TransactionAspectSupport classes. Those classes will interact with PlatformTransactionManager to commit transaction upon successful method execution or rollback upon exception. Exact behavior will be dependent on transaction propagation and isolation level settings, which can be set in @Transactional annotation.

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

How are you going to define a transaction in
Spring?

A

To use transactions in Spring Framework, you need to:

 Enable transaction management by using
@EnableTransactionManagement annotation on top of your Configuration class

 Create bean method in configuration class that will return bean implementing interface PlatformTransactionManager, examples of transactions managers:
 DataSourceTransactionManager
 JtaTransactionManager
 JpaTransactionManager
 …

 Use @Transactional annotation on top of classes or methods that should involve transaction management

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

What does @Transactional do?

A

@Transactional annotation can be used on top of classes or methods to enable transaction management for entire class or specified methods. When method with @Transactional annotation is called, invocation is proxied by TransactionInterceptor and TransactionAspectSupport which are using PlatformTransactionManager to manage transaction.

Transaction is being started at the beginning of the method (if none transaction exists), and it is being committed at the end of successful execution. Transaction can be rolled back upon exception being thrown. This behavior is dependent on transaction propagation type.

@Transactional annotation allows you to configure following attributes:
 Transaction Manager
 Propagation Type
 Isolation Level
 Timeout for Transaction
 Read Only Flag
 Define which exception types will cause transaction rollback
 Define which exception types will not cause transaction rollback

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

What is the
PlatformTransactionManager?

A

PlatformTransactionManager is an interface that is used by declarative Spring’s AOP Transaction Management to create, commit and rollback transactions.

PlatformTransactionManager contains following methods:
 getTransaction – returns currently active transaction or creates new one
 commit – commits transaction, or rolls back transaction if it was marked for rollback
 rollback – performs rollback of transaction

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

Is the JDBC template able to participate in an
existing transaction?

A

Yes, JDBC Template is able to participate in existing transaction. It will support both, transaction created with @Transactional annotation and also programmatically created transaction.

JDBC Template is able to participate in existing transaction by usage of DataSourceUtils and TransactionSynchronizationManager.

TransactionInterceptor and TransactionAspectSupport are also using
PlatformTransactionManager together with
DataSourceTransactionManager which will set transaction in
TransactionSynchronizationManager for JDBC Template (or other
components) to reuse.

20
Q

What is a transaction isolation level?

A

Transaction Isolation determines how changes made under one transaction are visible in other transactions and to other users of the system.

Higher isolation level means that changes from one transaction are not visible and lower isolation level means that changes from one transactions may “slip” into selects executed under other transaction.

Higher transaction isolation level make data being visible in more consistent way, lower transaction isolation level makes data less consistent but increases overall throughput and concurrency of the system.

21
Q

what is phantom read problem caused by concurrent transactions?

A

insertion / update of record by transaction A within a range selected by another transaction B will be visible to transaction B

Phantom read:
 Transaction A - first read
- select id, first_name, last_name from employees where id between 5 and 10
 Transaction B - write
- insert into employees values(7, ‘John’, ‘Doe’);
 Transaction A - second read
- select id, first_name, last_name from employees where id between 5 and 10

High Isolation Level will make second read returning same values as first read, lower isolation level will include new row with id 7 in second read.

To prevent phantom read, you need to pick isolation level that uses range locks (Isolation - Serializable).

22
Q

what is non-repeatable read problem in concurrent transactions?

A

update of record COMMITTED by transaction A will be seen in transaction B select

Non-repeatable read:
 Transaction A - first read
- select id, first_name, last_name from employees where id = 5
 Transaction B – write & commit
- update employees set last_name = ‘Doe’ where id = 5
 Transaction A - second read
- select id, first_name, last_name from employees where id = 5

High Isolation Level will make second read returning same values as first read, lower isolation level will read new values for record 5.

To prevent non-repeatable reads you need to use isolation level that uses readwrite locks on data being processed.

23
Q

what is dirty read problem in concurrent transactions problem?

A

update of record NOT COMMITTED by transaction A is visible in select of transaction B

Dirty read:
 Transaction A - first read
- select id, first_name, last_name from employees where id = 5
 Transaction B – write (commit does not have to happen)
- update employees set last_name = ‘Doe’ where id = 5
 Transaction A - second read
- select id, first_name, last_name from employees where id = 5

High Isolation Level will make second read returning same values as first read, lower isolation level will read new values for record 5, even if Transaction B will not commit the data.

To prevent dirty reads you need to use isolation level that prevents uncommitted changes by other transaction being visible in your transaction.

24
Q

what are the levels of transaction isolations for concurrent transactions?

A

Most Relational Databases support 4 transaction levels:
- Serializable
 Highest Isolation Level
 Read-Write Locks held until end of transaction (repeatable reads always consistent even other transactions update records)
 Range Locks held until end of transaction (prevent phantom read but put other transactions on hold to write into the range)

  • Repeatable Read
     Read-Write Locks held until end of transaction
  • Read Committed
     Read Locks held until end of select statement (therefore next read will be able to see updates from other transactions)
     Write Locks held until end of transaction
  • Read Uncommitted
     Lowest isolation level
     It is possible to see changes from other transactions that are not committed

In Spring Framework, you can use @Transactional annotation to set isolation level.

25
Q

comparison of transaction isolation levels

A

Serializable:
- phantom read : not possible
- non-repeatable read: not possible
- dirty read: not possible
- concurrency : very poor

repeatable read:
- phantom read : possible
- non-repeatable read: not possible
- dirty read: not possible
- concurrency : poor

read committed:
- phantom read : possible
- non-repeatable read: possible
- dirty read: not possible
- concurrency : good

read uncommitted:
- phantom read : possible
- non-repeatable read: possible
- dirty read: possible
- concurrency : very good

26
Q

What is @EnableTransactionManagement for?

A

@EnableTransactionManagement annotation is used on top of @Configuration class to enable annotation-driven transaction management by @Transactional annotation in Spring Framework.

When @EnableTransactionManagement is used, TransactionInterceptor and TransactionAspectSupport will be used to proxy each call to @Transactional class or method, which will use
PlatformTransactionManager to manage transaction.

@EnableTransactionManagement allows you to specify following values:
 Mode – sets advice mode for @Transactional annotation, indicates how calls to methods should be intercepted, PROXY is default mode, you can switch it to more advanced ASPECTJ weaving advice, which supports local calls
 Order – indicates order of advice execution when more then one advice applies to @Transactional join point
 proxyTargetClass – indicates whether CGLIB Proxy classes should be created or if JDK Proxies should be created (default), this field is used only when Mode is set to PROXY

27
Q

What does transaction propagation mean?

A

Transaction propagation defines how existing transaction is re-used when calling @Transactional method with transaction already running.

Transaction propagation can be defined in @Transactional annotation in propagation field as one of following options:

 REQUIRED - support a current transaction, create a new one if none exists

 SUPPORTS - support a current transaction, execute non-transactionally if none exists

 MANDATORY - support a current transaction, throw an exception if none exists

 REQUIRES_NEW - create a new transaction, and suspend the current transaction if one exists

 NOT_SUPPORTED - execute non-transactionally, suspend the current transaction if one exists

 NEVER - execute non-transactionally, throw an exception if a transaction exists

 NESTED - execute within a nested transaction if a current transaction exists, behave like REQUIRED else

28
Q

What happens if one @Transactional annotated method is calling another @Transactional annotated method on the same object instance?

A

JDK Proxy and CGLIB Proxy in Spring Beans AOP do not support self invocation, so when one method with @Transactional annotation calls different method with @Transactional annotation from the same class, nothing happens, transaction interceptor will not be called.

Also, if @Transactional method is called by another method not annotated in the same class, transaction interceptor will not be called.

To enable self invocation support, you need to configure Spring Aspects with AspectJ, to do that you need to:
 Have dependency to spring-aspects
 Include aspectj-maven-plugin
 Configure Transaction Support with
@EnableTransactionManagement(mode = AdviceMode.ASPECTJ)

29
Q

Where can the @Transactional annotation be used? What is a typical usage if you put it at class level?

A

@Transactional can be used on top of class or method, in classes or
interfaces.

If used on top of class, it applies to all public methods in this class.

If used on top of method, it needs to have public access modifier, if used on top of protected / package-visible / private method, transaction management will not be applied.

30
Q

What does declarative transaction
management mean?

A

Declarative transaction management means that instead of handling transactions manually through the code, methods which should be executed in transactions are declared with @Transactional annotation.

manual transaction handling need to get connection, set rollback and close in code explicitly

31
Q

What is the default rollback policy? How can
you override it?

A

Default rollback policy in Spring Framework is set to automatic rollback, but only when unchecked exception is being thrown from the method annotated with @Transactional annotation.

When checked exception is being thrown from the method, transaction is not being rolled back.

You can override this policy by setting rollbackFor /
rollbackForClassName or noRollbackFor / noRollbackForClassName
field in @Transactional annotation.

32
Q

What is the default rollback policy in a JUnit test, when you use
the @RunWith(SpringJUnit4ClassRunner.class) in JUnit 4 or
@ExtendWith(SpringExtension.class) in JUnit 5, and annotate your @Test annotated method with @Transactional?

A

Default rollback policy in @Test methods annotated with @Transactional is always rollback. This means that after test execution transaction will always be rolled back.

The reason for this is that each test method should be able to
change state of database or call other classes that will change state of the database, however for the tests to be repeatable, changes should be reverted after @Test method execution.

You can change this behavior by using @Rollback annotation set to false.

33
Q

Why is the term “unit of work” so important ?

A

Unit of work is a generic term to describe, set of tasks that are performing some changes on the data, with assumption that all changes needs to be performed, or no changes should be performed at all.

In Relational Databases, Unit of Work can be represented by Database Transaction, which Atomic nature describes “all-or-nothing” behavior described above.

In context of JPA/Hibernate, Unit of Work tracks all changes made to the Data Objects representing entries in the database, and once done, ORM figures out all changes that needs to be applied to the database. This way amount of calls to the database can be minimized by aggregating all changes into one call. e.g. multiple updates on same record will result into 1 sql only for aggregated change

34
Q

why does JDBC AutoCommit violate unit of work pattern?

A

JDBC AutoCommit violates Unit of Work, because it makes every SQL statement being invoked in a separate transaction that is committed after SQL is executed, this makes impossible to implement Unit of Work consisting of multiple SQL operations.

35
Q

What do you need to do in Spring if you would
like to work with JPA?

A
  1. Declare maven dependencies:
     JPA API - javax.persistence:javax.persistence-api
     Spring ORM - org.springframework:spring-orm
     ORM of your choice, for example - org.hibernate:hibernate-core
     Database Driver, for example - org.hsqldb: hsqldb
     Optionally, but recommended, Spring Data JPA - org.springframework.data:spring-data-jpa to provide repositories
  2. Define DataSource Bean
  3. Define PlatformTransactionManager, in case of JPA JpaTransactionManager
  4. Define EntityManagerFactoryBean
     LocalContainerEntityManagerFactoryBean for standalone application
     EntityManagerFactory from JNDI (in application server env)
     LocalEntityManagerFactoryBean for Test purposes
  5. Define @Entity classes with at least one @Id field
  6. Define DAO classes, or use Spring Data JPA Repositories
36
Q

Are you able to participate in a given transaction in Spring while working with JPA?

A

Yes, JPA in Spring uses JpaTransactionManager, which supports cases when DataSource is used directly, so it allows mixing JPA and JDBC code under one transaction.

e.g. service method annotated with @Transactional can invoke jpa repository dao methods and jdbc template dao method. both jpa and jdbc methods will reuse the existing transaction connection created by the service method.

When using Spring Framework on Java EE platform, it is possible to reuse existing transactions as well by using JtaTransactionManager, which will delegate transaction management to Java EE container.

37
Q

Which PlatformTransactionManager(s) can you
use with JPA?

A

 JpaTransactionManager – recommended when working with one database and one Entity Manager
if used with multiple data sources, transactions can only rollback for individual data source, but not changes in different data sources altogether.

 JtaTransactionManager – recommended when working with multiple databases and Entity Managers, or when working with multiple databases and other transactional resources, for example
one transaction needs to span Databases and JMS Topic

38
Q

How does Spring Boot make JPA configuration in spring easier?

A

 Providing spring-boot-starter-data-jpa dependency which includes all required dependencies e.g. spring ORM, ORM, DB driver

 Providing auto-configuration for JPA

 Automatically defines PlatformTransactionManager, EntityManager and other required beans

 Allows Data Source to be configured via properties

 Provides out-of-the-box support for Hikari Connection Pool

 Provides default properties to JPA

 Automatically creates DAO beans for Repositories

39
Q

What is a Repository interface?

A

Repository interface is a Java interface that describes Dao with expected behaviors, based on which Spring Data will automatically generate Dao logic. Repository interface takes Domain Class and ID of
type to manage. &laquo_space;entityClassName, idPropertyClassType&raquo_space;

Custom Repository interface needs to extend one of following interface:
 Repository – basic marker repository
 CrudRepository – adds generic methods for CRUD operations
 PagingAndSortingRepository – adds findAll methods for paging/sorting
 JpaRepository – JPA specific extension of Repository

40
Q
  • How do you define a Repository interface?
A

To define Repository interface, you need to follow those steps:
 Create Java Interface that extends one of: Repository, CrudRepository, PagingAndSortingRepository, JpaRepository
 Create class with @Entity annotation
 Inside @Entity class, create a simple primary key annotated with @Id annotation or create class that will represent complex key annotated with @EmbeddedId annotation at field level and
@Embeddable at key class definition level
 Use @EnableJpaRepositories to point out package to scan for Repositories

41
Q

Why is repository an interface not a class?

A

Repository interface is an interface, not a class for Spring Data to be able to use JDK Dynamic Proxy to intercept all calls to repository and also to allow creation of custom base repositories for every Dao based on SimpleJpaRepository configured at @EnableJpaRepositories level.

42
Q

What is the naming convention for finder methods in a Repository interface? (syntax)

A

find[limit]By[property/properties expression][comparison][ordering operator]

limit – result of the query can be limited by usage of first/top keyword
 findFirst10ByLastname

property/properties expression – result will be filtered based on property of entity, multiple properties can be used with usage of And, Or keyword
 findByLastnameAndFirstname

comparison – comparison mode can be specified after specifying property used for filtering
 findByFirstnameIs
 findByFirstnameEquals

ordering operator – optionally you can specify ordering operator at the end of method name
 findByLastnameOrderByFirstnameAsc

43
Q
  • How are Spring Data repositories implemented
    by Spring at runtime?
A

Spring Repositories are implemented at runtime by SimpleJpaRepository by default.

When application context is starting up, Spring will scan for all classes annotated with @Configuration.
When @Configuration class with @EnableJpaRepositories will be detected, JpaRepositoriesRegistrar with JpaRepositoryConfigExtension will be used to create beans for repositories in packages pointed out by basePackages field in @EnableJpaRepositories.
JpaRepositoryFactoryBean will use JpaRepositoryFactory to create beans based on bean definitions and by default will create
instance of SimpleJpaRepository class for each Repository interface.

44
Q

how to customize spring data repository implementation beans?

A

Class used for implementation of Repository interface can be customized on:
 Global level, by using repositoryBaseClass field from @EnableJpaRepositories annotation. create a custom class to be pointed to.

 Single Dao/Repository by creating separate interface and Impl class for behavior that you want to customize. it can customize only selected repositories

45
Q

What is @Query used for?

A

@Query annotation can be used on top of Repository method, and with it you can specify query that should be used by JPA. When declaring one on top of finder method, specified query will be used, instead of generating one automatically based on finder method name.

Using @Query annotation allows you to achieve more control and flexibility of the JPA query that will be executed.