Prev Next

Spring / Spring Data Access

1. Explain JdbcTemplate in Spring framework. 2. Advantages of Spring JDBC Template over standard JDBC. 3. How could I access Hibernate using Spring? 4. How can we integrate Spring and Hibernate using HibernateDaoSupport? 5. What are the advantages of transaction management in Spring Framework? 6. Which Transaction management type is preferred in Spring? 7. Explain DataAccessException in Spring. 8. How do I configure DAO in Spring? 9. What are the ORMs does Spring supports? 10. List some of the no sql databases does spring support? 11. Difference between Spring Data-JPA versus JPA. 12. Give few examples of spring callbacks used in JdbcTemplate. 13. What are the exceptions thrown by the Spring DAO classes? 14. What is Spring Data JPA? 15. Difference between CrudRepository and JpaRepository interfaces in Spring Data JPA. 16. What is SQLExceptionTranslator in Spring DAO? 17. Difference between Spring Data JPA and hibernate. 18. How do I decide between JPA and Spring JdbcTemplate? 19. What is PreparedStatementCreator in Spring Data framework? 20. What is SQLProvider in Spring Data framework? 21. What is BatchPreparedStatementSetter in Spring Data? 22. Which is the better way of using JDBC in Spring? 23. What template does Spring JDBC provide to access database? 24. What are the native NativeJdbcExtractor in Spring? 25. Explain Global and Local transactions in Spring. 26. How do we roll back a declarative transaction in Spring? 27. Different types of isolation in spring transaction management. 28. Types of propagation in Spring transaction management. 29. Spring: How do I rollback a declarative transaction? 30. Spring: List out the role of TransactionDefinition interface. 31. What are the benefits of the Spring transaction management ? 32. Why Spring Declarative transaction management is preferred over programmatic? 33. Spring @Transactional Annotation. 34. What is the principle of Declarative transaction management in Spring? 35. How does @Transactional works in Spring? 36. How do you prevent SQL Injection in Java Code? 37. Advantages of using @RepositoryRestResource annotation in Spring Data REST. 38. When to use @RestController vs @RepositoryRestResource annotations in Spring. 39. How do I unit test spring data repositories? 40. What are the different isolation levels of DBMS? 41. What is the difference between serializable and repeatable read isolation level? 42. Explain serializable isolation level. 43. What is the ISOLATION_DEFAULT in spring transaction management. 44. What is the default propagation behavior of spring transaction management? 45. Does the transaction rollback on exception in spring declarative transaction management? 46. Explain NoRepositoryBean spring annotation. 47. How do you handle High-volume Transaction Processing in J2EE? 48. Explain Dirty read. 49. Difference between non-repeatable read and phantom read. 50. What is 2 phase commit? 51. Difference between JDBC and connection pooling.
Could not find what you were looking for? send us the question and we would be happy to answer your question.

Explain JdbcTemplate in Spring framework.

JdbcTemplate class provides many convenience methods for doing things such as converting database data into primitives or objects, executing prepared and callable statements, and providing custom database error handling.

Advantages of Spring JDBC Template over standard JDBC.

The Spring JDBC Template has the following advantages compared with standard JDBC.

The Spring JDBC template allows to clean-up the resources automatically, e.g. release the database connections.

The Spring JDBC template converts the standard JDBC SQLExceptions into RuntimeExceptions. This allows the programmer to react more flexible to the errors. The Spring JDBC template converts also the vendor specific error messages into better understandable error messages.

How could I access Hibernate using Spring?

There are 2 ways to access Hibernate with Spring.

  • Inversion of Control with a Hibernate Template and Callback.
  • Extending HibernateDAOSupport and Applying an AOP Interceptor node.
How can we integrate Spring and Hibernate using HibernateDaoSupport?

Use Spring's SessionFactory called LocalSessionFactory to integrate Spring and HIbernate. The integration process is of 3 steps.

  1. Configure the Hibernate SessionFactory.
  2. Extend a DAO Implementation from HibernateDaoSupport.
  3. Wire in Transaction Support with AOP.
What are the advantages of transaction management in Spring Framework?

It supports declarative transaction management.

It provides a consistent programming model across different transaction APIs such as JTA, JDBC, Hibernate, JPA, and JDO.

It provides a simpler API for programmatic transaction management than a number of complex transaction APIs such as JTA.

It integrates very well with Spring’s various data access abstractions.

Which Transaction management type is preferred in Spring?

Declarative transaction management is preferred over programmatic transaction management though it is less flexible than programmatic transaction management, which allows you to control transactions through your code.

Explain DataAccessException in Spring.

This exception hierarchy aims to let user code find and handle the kind of error encountered without knowing the details of the particular data access API in use (for example, JDBC).

This class is a runtime exception, there is no need for user code to catch it or subclasses if any error is to be considered fatal (the usual case).

How do I configure DAO in Spring?

Mark the DAO class with @Repository annotation.

Entity manager can be configured by @PersistenceContext at property level.

What are the ORMs does Spring supports?

Spring supports the following ORMS.

  • Hibernate.
  • iBatis.
  • JPA (Java Persistence API).
  • TopLink.
  • JDO (Java Data Objects).
List some of the no sql databases does spring support?
  • MongoDB, Open-source document database.
  • Cassandra Database that provides scalability and high availability without compromising performance.
  • Redis structure server wherein keys can contain strings, hashes, lists, sets, and sorted sets.
  • HBase Hadoop database, a distributed and scalable big data store.
Difference between Spring Data-JPA versus JPA.

JPA is an specification while Hibernate is a particular implementation of that specification.

Spring Data JPA is on top of JPA adding another layer of abstraction, standardizing the design for the support of your Persistence Layer in a Spring context. Those defined interfaces (known to Spring) provide the services that the framework handles using JPA to serve the results.

Give few examples of spring callbacks used in JdbcTemplate.

The Spring callbacks in JdbcTemplate are PreparedStatementCallback, ResultSetExtractor, RowCallbackHandler and RowMapper.

What are the exceptions thrown by the Spring DAO classes?

Spring DAO classes throw exceptions that are subclasses of org.springframework.dao. DataAccessException.

Spring translates technology-specific exceptions like SQLException to its own exception class hierarchy with the DataAccessException as the root exception that are generic and easy to understand. These exceptions wrap the original exception.

What is Spring Data JPA?

Spring Data JPA aims to significantly improve the implementation of data access layers by reducing the effort to the amount that is actually needed. As a developer you write your repository interfaces, including custom finder methods, and Spring will provide the implementation automatically.

Difference between CrudRepository and JpaRepository interfaces in Spring Data JPA.

JpaRepository extends PagingAndSortingRepository that extends CrudRepository.

CrudRepository mainly provides CRUD operations.

PagingAndSortingRepository provide methods to perform pagination and sorting of records.

JpaRepository provides JPA related methods such as flushing the persistence context and deleting of records in batch.

Due to their inheritance nature, JpaRepository will have all the behaviors of CrudRepository and PagingAndSortingRepository. So if you don't need the repository to have the functions provided by JpaRepository and PagingAndSortingRepository , use CrudRepository.

What is SQLExceptionTranslator in Spring DAO?

SQLExceptionTranslator is a strategy interface that translates between SQLExceptions and Spring's data access strategy-agnostic DataAccessException hierarchy.

The returned DataAccessException is supposed to contain the original SQLException as root cause.

Difference between Spring Data JPA and hibernate.

spring-data adds powerful and useful API that helps with complex queries.

Spring JPA will provide you abstraction from writing SQL and even some HQL using query method declaration. Spring JPA shines with its query generation but when you want a purely hibernate solution you can customize as needed as spring JPA is still based on hibernate.

How do I decide between JPA and Spring JdbcTemplate?

Use Spring JdbcTemplate if you don't want to access your database schema via a domain model. Using JPA you need to make sure that database schema maps correctly to the domain model.

Performance is almost similar at both spring JdbcTemplate and JPA.

What is PreparedStatementCreator in Spring Data framework?

PreparedStatementCreator is one of the most commonly used interfaces for writing data to the database. createPreparedStatement() is a method that can be used to create and return PreparedStatement from the Connection argument, and exception handling is automatically taken care of. When this interface is implemented, a different interface SqlProvider can also be implemented which has a method called getSql().

This method is useful for providing sql strings to the JdbcTemplate. It does not handle SQLExceptions.

What is SQLProvider in Spring Data framework?

SQLProvider is mainly used for debugging. It has only one method called getSql() and it is implemented using PreparedStatementCreator implementers.

What is BatchPreparedStatementSetter in Spring Data?

BatchPreparedStatementSetter is used to update more than a single row in bulk.This interface provides two methods,

  • setValues( PreparedStatement ps, int i) throws SOL exception.
  • int getBatchSize.

Which is the better way of using JDBC in Spring?

For better performance and easy implementation JDBC can be used with the template class called JdbcTemplate.

What template does Spring JDBC provide to access database?
  • JdbcTemplate.
  • NamedParameterJdbcTemplate.
  • SimpleJdbcTemplate
What are the native NativeJdbcExtractor in Spring?
  • SimpleNativeJdbcExtractor.
  • C3P0NativeJdbcExtractor .
  • CommonsDbcpNativeJdbcExtractor .
  • JBossNativeJdbcExtractor.
Explain Global and Local transactions in Spring.

Global transactions helps manage multiple transactional resources like relational databases and message queue. Global transactions are managed through JTA and JNDI.

Local transactions are resource-specific like JDBC connection. Local Transactions can interact with multiple transactional resources.

How do we roll back a declarative transaction in Spring?

Use rollback-for and no-rollback-for attributes with transactional definition.

Different types of isolation in spring transaction management.
  • ISOLATION_DEFAULT: default isolation.
  • ISOLATION_READ_COMMITTED: dirty reads are prevented, non-repeatable and phantom reads are allowed.
  • ISOLATION_READ_UNCOMMITTED : dirty reads are allowed, no-repeatable and phantom reads are allowed.
  • ISOLATION_REPEATABLE_READ : dirty reads and non-repeatable reads are prevented but phantom reads are allowed.
  • ISOLATION_SERIALIZABLE : dirty , non- repeatable reads and phantom reads are prevented.
Types of propagation in Spring transaction management.

There are 7 propagation levels in spring.

  • PROPAGATION_MANDATORY : supports current transaction and throws exception if no transaction available.
  • PROPAGATION_NESTED: runs with nested transaction.
  • PROPAGATION_NEVER : does not run with current transaction and throws exception if current transaction exits.
  • PROPAGATION_NOT_SUPPORTED : runs non -transactionaly and does not support current transaction.
  • PROPAGATION_REQUIRED : runs with current transaction and create one if does not exist.
  • PROPAGATION_REQUIRES_NEW : creates new transaction and suspends if exits any.
  • PROPAGATION_SUPPORTS: runs current transaction and runs non -transactionally.
  • Spring: How do I rollback a declarative transaction?

    Use rollback-for and no-rollback-for attributes with transactional definition.

    Spring: List out the role of TransactionDefinition interface.
    • Isolation.
    • Propagation.
    • Timeout.
    • Read-only status.
    What are the benefits of the Spring transaction management ?

    The Spring Framework provides a consistent abstraction for transaction management that delivers the following benefits:

    Provides a consistent programming model across different transaction APIs such as JTA, JDBC, Hibernate, JPA, and JDO.

    Supports declarative transaction management.

    Provides a simpler API for programmatic transaction management than a number of complex transaction APIs such as JTA.

    Integrates very well with Spring's various data access abstractions.

    Why Spring Declarative transaction management is preferred over programmatic?

    Declarative transaction management provides least impact on application code and hence is most consistent with the ideals of a non-invasive lightweight container.

    Spring @Transactional Annotation.

    Transactional annotation is the convenient and readable and is currently the recommended way to handle transactions in Spring.

    By using @Transactional, many important aspects such as transaction propagation are handled automatically.

    What is the principle of Declarative transaction management in Spring?

    Declarative transaction support uses AOP (Aspect Oriented Programming) as its foundation.

    How does @Transactional works in Spring?

    @Transactional annotation is based on AOP concept.

    When you annotate a method with @Transactional, Spring dynamically creates a proxy that implements the same interface(s) as the class you are annotating. And when clients make calls into your object, the calls are intercepted and the behaviors gets injected via the proxy mechanism.

    @Transactional annotation works similar to transactions in EJB.

    How do you prevent SQL Injection in Java Code?

    You can use PreparedStatement to avoid SQL injection in Java code. Use of the PreparedStatement for executing SQL queries not only provides better performance but also shield your Java and J2EE application from SQL Injection attack.

    Advantages of using @RepositoryRestResource annotation in Spring Data REST.

    @RepositoryRestResource annotation exposes a data repository as a RESTFul resource. This annotiation is similar to @RestController annotation in Spring MVC.

    When to use @RestController vs @RepositoryRestResource annotations in Spring.

    @RestController annotation renders as Restful resource within a Controller while @RepositoryRestResource annotation exposes repository itself as a RESTful resource.

    How do I unit test spring data repositories?

    Unit testing can be achieved by mocking all JPA data API that we invoke.

    However the unit testing for spring data respositories is not required since we don't write any API implementations. Integration testing is more ideal than unit testing.

    What are the different isolation levels of DBMS?
    • Serializable,
    • Repeatable reads,
    • Read committed,
    • and read uncommitted.
    What is the difference between serializable and repeatable read isolation level?

    In a Repeatable Read isolation level, new rows can be inserted into the dataset.

    In a Serializable isolation level all the rows are locked for the duration of the transaction, no insert,update or delete is allowed.

    Explain serializable isolation level.

    This is the highest isolation level.

    With a lock-based concurrency control DBMS implementation, serializability requires read and write locks (acquired on selected data) to be released at the end of the transaction. Also range-locks must be acquired when a SELECT query uses a ranged WHERE clause, especially to avoid the phantom reads phenomenon.

    When using non-lock based concurrency control, no locks are acquired; however, if the system detects a write collision among several concurrent transactions, only one of them is allowed to commit.

    What is the ISOLATION_DEFAULT in spring transaction management.

    Spring ISOLATION_DEFAULT uses the default isolation level of the underlying datastore.

    What is the default propagation behavior of spring transaction management?

    PROPAGATION_REQUIRED is the default propagation property of @Transactional annotation.

    Does the transaction rollback on exception in spring declarative transaction management?

    By default configuration only unchecked exceptions (that is, subclasses of java.lang.RuntimeException) are rollbacked and the transaction will still be commited in case of checked exceptions.

    To enable rollbacking on checked exceptions add the parameter rollBackFor to the @Transactional attribute, for example, rollbackFor=Exception.class.

    @Transactional(rollbackFor = Exception.class)
    
    Explain NoRepositoryBean spring annotation.

    This annotation excludes repository interfaces from being picked up and prevents getting an instance being created.

    The common usage of this annotation is when providing an extended base interface for all repositories in combination with a custom repository base class to implement methods declared in that intermediate interface. In this case you typically derive your concrete repository interfaces from the intermediate one but prevents creating a Spring bean for the intermediate interface.

    How do you handle High-volume Transaction Processing in J2EE?

    Leverage batch processing to process the work off-line in batch.

    Use Real-time asynchronous processing such as fine-grained timers or asynchronous event triggers (such as JMS) to pass responsibility from on-line to back-end function.

    Explain Dirty read.

    When one transaction reads changes made by another transaction that has not yet been committed it is called dirty read. It is dangerous and unusual to use this type of transaction because the read data might get rolled back.

    Difference between non-repeatable read and phantom read.

    Both non-repeatable and phantom reads have to do with data modification operations from a different transaction, which were committed after your transaction began, and then read by your transaction.

    Non-repeatable reads are when your transaction reads committed UPDATES from another transaction. The same row now has different values than it did when your transaction began.

    Phantom reads are similar but when reading from committed INSERTS and/or DELETES from another transaction. There are new rows or rows that have disappeared since you began the transaction.

    Dirty reads are similar to non-repeatable and phantom reads, but relate to reading UNCOMMITTED data, and occur when an UPDATE, INSERT, or DELETE from another transaction is read, and the other transaction has NOT yet committed the data. It is reading "in progress" data, which may not be complete, and may never actually be committed.

    What is 2 phase commit?

    Two phase commit is used in distributed environment where multiple transaction take part in distributed transaction process.

    In two phase commit, commit or rollback is performed in 2 phases:

    Commit request phase: In this phase main process or coordinator process send precommit request to all other process that it has completed its process successfully and ready to commit if all the votes are 'yes' then they go ahead for next phase. And if 'No' then rollback is performed.

    Commit phase: Based on the acknowledgement vote if all the votes are yes then commit is done otherwise rollbacked.

    Difference between JDBC and connection pooling.

    JNDI creates a connection pool. Connection pool is an environment on the server where JNDI and Database encapsulated to for Type4 connectivity.

    JDBC: A Java API that enables Java programs to execute SQL statements. This allows Java programs to interact with any SQL-compliant database.

    «
    »
    Web services

    Comments & Discussions