Spring Interview Module 3 Data Access Flashcards
What is checked exceptions?
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
what is unchecked exceptions and why Spring prefers unchecked exceptions?
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
What is the data access exception hierarchy?
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
what is a data source in java?
Data Source is represented by generic interface javax.sql.DataSource which represent any data source for sql database.
how to configure data source in spring?
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
Which bean is very useful for development/test databases?
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.
What is the Template design pattern?
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.
what is the JDBC template?
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
What is a callback?
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
What are the three JdbcTemplate callback interfaces that can be used with queries (result set)?
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
what are jdbc template callback methods for statements?
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
Can you execute a plain SQL statement with
the JDBC template?
Yes, JDBC Template allows execution of plain SQL statements with following
methods:
query
queryForList
queryForObject
queryForMap
queryForRowSet
execute
update
batchUpdate
When does the JDBC template acquire (and release) a connection, for every method called or once per template? Why?
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 does the JdbcTemplate support generic queries? How does it return objects and lists/maps of objects?
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
Is a transaction a cross cutting concern? How is it implemented by Spring?
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 are you going to define a transaction in
Spring?
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
What does @Transactional do?
@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
What is the
PlatformTransactionManager?
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