Spring-Jdbc
Advantages of spring jdbc?
spring internally uses connection parameters
spring opens the connection and closing the connection
spring creates statement logic by using jdbcTemplate class
spring handles the transaction
spring exception handling
DriverManagerDataSource?
The simple implementation of standard jdbc data source interface. Configuring a plain old jdbc driver via bean properties and returns new connection for every get Connection call.
this is not a actual connection pool.it does not contains connection pools. it creates a new connection for every call
it used in outside J2EE container or standard alone apps
in j2ee container, is recommended to use a jndi data source provided by the container such as “JndiObjectFactoryBean”
JndiObjectFactoryBean “it has the actual connection pools. in real time apps we are using JndiObjectFactoryBean with data source
JdbcTemplate?
This is the central class in the jdbc core pkg.it simplifies the use of jdbc code
This class internally having the statement logic
This class excutes sql queries ,updates,initiating iteration over results and catching jdbc exceptions and translating them to generic
QueryForMethods?
We are using these methods whenever we perform aggregate functions results and must be one row and one column results
We have many queryFormethods
1. QueryForInt()
2. queryForString()
3. queryForObject()
4. queryForMap()
5. queryForList()
6/ queryForFloat() ----etc
In real time most of the cases we use 1
These all methods are used for select operation only but not non select operation
What are the concepts we use curd operations in spring Jdbc?
1.insert/update/delete=====èjdbcTemplate.execute();
2.select with aggregate functions like count(*),max,min ---etc=====èqueryForInt/Object/Map
3.select with tables ex. select sno,sname from student=èRowMapper
What is RowMaper?
RowMapper is an interface used to map a row with an object. while working with rowmapper interface
spring provides,statement,connection,resultset creation and closeting is done by spring
exception Handling is spring
looping and creating the list is done by spring
the implementation of this interface is available in “ColumnRowMapper”
What is ResultSetExtracter?
It is interface
It provides similar to RowMapper interface.but it doesn’t create list object
while working with this we need to override the extractData () method
The implementation class is”RowMapperResultSetExtractor”
What is RowCallbackHandler?
It is an interface.It provides the features like RowMapper interface but it doesn’t create list object
while working with this interface we need to override the ProcessRow () method
What is PreparedStatementCreator?
It is an interface.It is used to create preparedStatement using connection
The implementation class of PreparedStatementCreator is”SimplePreparedStatementCreator”
What is PreparedStatementSetter?
It is an interface. Used to set the values to prepared Statement
The implementation class of this interface is “ArgPreparedStatement”
PreparedStatementCallback?
This is an interface. The implementation is used to execute the prepared Statement
CallableStatementCreaterImpl ?
àIt is a class .it creates callable Statement
CallableStatementCallback?
It executes the callable Statement
What is the use of batch Update?
àWhenever we want to execute multiple queries it take some time to execute so it will decrease the performance of an application.
àIf we use batch Update then to decrease the execution time of an application so it will increase the performance of an application
ContextLoaderListener?
àIt is used to read the spring configuration file
àIt will identify the config file using”contextConfigLocation” context parameter
15. What is DAO?
The java class that contains only persistent logic and separates that logic from other logics of application is called DAO
15. DataSourceTransactionManager?
It contains the transaction logic like con.setAutoCoomit(false),con.commit()……etc to apply the transaction it excepts the data Source so we are injecting data Source using this it will get con to apply transaction
What kind of exceptions those spring DAO classes throw?
The spring’s DAO class does not throw any technology related exceptions such as SQLException. They throw exceptions which are subclasses of DataAccessException.
What is DataAccessException?
DataAccessException is a RuntimeException. This is an Unchecked Exception. The user is not forced to handle these kinds of exceptions.
How can you configure a bean to get DataSource from JNDI?
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName">
<value>java:comp/env/jdbc/myDatasource</value>
</property>
</bean>
<property name="jndiName">
<value>java:comp/env/jdbc/myDatasource</value>
</property>
</bean>
How can you create a DataSource connection pool?
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driver">
<value>${db.driver}</value>
</property>
<property name="url">
<value>${db.url}</value>
</property>
<property name="username">
<value>${db.username}</value>
</property>
<property name="password">
<value>${db.password}</value>
</property>
</bean>
<property name="driver">
<value>${db.driver}</value>
</property>
<property name="url">
<value>${db.url}</value>
</property>
<property name="username">
<value>${db.username}</value>
</property>
<property name="password">
<value>${db.password}</value>
</property>
</bean>
How JDBC can be used more efficiently in spring framework?
JDBC can be used more efficiently with the help of a template class provided by spring framework called as JdbcTemplate.
How JdbcTemplate can be used?
· With use of Spring JDBC framework the burden of resource management and error handling is reduced a lot. So it leaves developers to write the statements and queries to get the data to and from the database.
· JdbcTemplate template = new JdbcTemplate(myDataSource);
A simple DAO class looks like this.
A simple DAO class looks like this.
· public class StudentDaoJdbc implements StudentDao {
private JdbcTemplate jdbcTemplate;
private JdbcTemplate jdbcTemplate;
· public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
more..
}
The configuration is shown below.
this.jdbcTemplate = jdbcTemplate;
}
more..
}
The configuration is shown below.
· <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource">
<ref bean="dataSource"/>
</property>
</bean>
<bean id="studentDao" class="StudentDaoJdbc">
<property name="jdbcTemplate">
<ref bean="jdbcTemplate"/>
</property>
</bean>
<bean id="courseDao" class="CourseDaoJdbc">
<property name="jdbcTemplate">
<ref bean="jdbcTemplate"/>
</property>
</bean>
<property name="dataSource">
<ref bean="dataSource"/>
</property>
</bean>
<bean id="studentDao" class="StudentDaoJdbc">
<property name="jdbcTemplate">
<ref bean="jdbcTemplate"/>
</property>
</bean>
<bean id="courseDao" class="CourseDaoJdbc">
<property name="jdbcTemplate">
<ref bean="jdbcTemplate"/>
</property>
</bean>
How do you write data to backend in spring using JdbcTemplate?
The JdbcTemplate uses several of these callbacks when writing data to the database. The usefulness you will find in each of these interfaces will vary. There are two simple interfaces. One is PreparedStatementCreator and the other interface is BatchPreparedStatementSetter.
Explain about PreparedStatementCreator?
PreparedStatementCreator is one of the most common used interfaces for writing data to database. The interface has one method createPreparedStatement().
· PreparedStatement createPreparedStatement(Connection conn)
throws SQLException;
When this interface is implemented, we should create and return a PreparedStatement from the Connection argument, and the exception handling is automatically taken care off. When this interface is implemented, another interface SqlProvider is also implemented which has a method called getSql() which is used to provide sql strings to JdbcTemplate.
throws SQLException;
When this interface is implemented, we should create and return a PreparedStatement from the Connection argument, and the exception handling is automatically taken care off. When this interface is implemented, another interface SqlProvider is also implemented which has a method called getSql() which is used to provide sql strings to JdbcTemplate.
Explain about BatchPreparedStatementSetter?
· If the user what to update more than one row at a shot then he can go for BatchPreparedStatementSetter.
This interface provides two methods setValues(PreparedStatement ps, int i) throws SQLException;
int getBatchSize();
The getBatchSize() tells the JdbcTemplate class how many statements to create. And this also determines how many times setValues() will be called.
int getBatchSize();
The getBatchSize() tells the JdbcTemplate class how many statements to create. And this also determines how many times setValues() will be called.
Explain about RowCallbackHandler and why it is used?
· In order to navigate through the records we generally go for ResultSet. But spring provides an interface that handles this entire burden and leaves the user to decide what to do with each row. The interface provided by spring is RowCallbackHandler. There is a method processRow() which needs to be implemented so that it is applicable for each and everyrow.
void processRow(java.sql.ResultSet rs);
What is JDBC abstraction and DAO module?
· Using this module we can keep up the database code clean and simple, and prevent problems that result from a failure to close database resources. A new layer of meaningful exceptions on top of the error messages given by several database servers is bought in this module. In addition, this module uses Spring’s AOP module to provide transaction management services for objects in a Spring application.
How can u integrate spring and hibernate with and without hibernate configuration file?
· Without configuration file we can integrate spring and hibernate for this we need to write HiberanteUtil classes’ .from this classes we need to get the connection from database
· With configuration file we need to configure the LocalSessionFactory bean in spring configuration file using configLocation property
· We can integrate spring and hibernate with and without hibernate configuration file
How to integrate spring and struts?
· We need to configure the spring configuration file in struts-config.xml with ContextLoaderPlugIn class with “contextConfiLocation”property
· <plug-in className=”--.ContextLoaderPlugIn”>
· <set-property property=”contextConfigLocation”value=”/WEB-INF/action-servlet.xml”/>
· </plug-in>
What is the default spring configuration file?
· In struts if are not giving any struts config file name in the web.xml using config init parameter then it takes struts-default.xml
· In spring, if are not giving any spring configuration file name in the struts-config.xml using contextConfigLocation property. if we are not configuring property it takes the by default “ActionServletName-servlet.xml”
How to delegate(forward) a struts request to spring?
· To forward a struts request to spring we need to configure the “DelegateActionProxy” class in struts-config.xml
· Struts-config.xml
· <action path=”/StudentAction” type=”--. DelegateActionProxy”/>
· Action-servlet.xml
· <bean name=”/StudentAction” type=”--.StudentAction”/>
· Here <action/> tag path and <bean/> name both must be same
What is HibernateTransactionManager?
· It is a simple java class it contains the transaction logic like session.beginTransaction(),tx.commit(),tx.rollback()……….etc
How would you integrate Spring and Hibernate using HibernateDaoSupport?
· This can be done through Spring’s SessionFactory called LocalSessionFactory. The steps in integration process are:
a.) Configure the Hibernate SessionFactory
b.) Extend your DAO Implementation from HibernateDaoSupport
c.) Wire in Transaction Support with AOP
a.) Configure the Hibernate SessionFactory
b.) Extend your DAO Implementation from HibernateDaoSupport
c.) Wire in Transaction Support with AOP
What are object/relational mapping integration module?
Spring also supports for using of an object/relational mapping (ORM) tool over straight JDBC by providing the ORM module. Spring provide support to tie into several popular ORM frameworks, including Hibernate, JDO, and iBATIS SQL Maps. Spring’s transaction management supports each of these ORM frameworks as well as JDBC.
When to use programmatic and declarative transaction management ?
Programmatic transaction management is usually a good idea only if you have a small number of transactional operations.
On the other hand, if your application has numerous transactional operations, declarative transaction management is usually worthwhile. It keeps transaction management out of business logic, and is not difficult to configure.
Programmatic transaction management is usually a good idea only if you have a small number of transactional operations.
On the other hand, if your application has numerous transactional operations, declarative transaction management is usually worthwhile. It keeps transaction management out of business logic, and is not difficult to configure.
Explain about the Spring DAO support ?
The Data Access Object (DAO) support in Spring is aimed at making it easy to work with data access technologies like JDBC, Hibernate or JDO in a consistent way. This allows one to switch between the persistence technologies fairly easily and it also allows one to code without worrying about catching exceptions that are specific to each technology.

What are the exceptions thrown by the Spring DAO classes ?
Spring DAO classes throw exceptions which are subclasses of DataAccessException(org.springframework.dao.DataAccessException).Spring provides a convenient translation from technology-specific exceptions like SQLException to its own exception class hierarchy with the DataAccessException as the root exception. These exceptions wrap the original exception.
The Data Access Object (DAO) support in Spring is aimed at making it easy to work with data access technologies like JDBC, Hibernate or JDO in a consistent way. This allows one to switch between the persistence technologies fairly easily and it also allows one to code without worrying about catching exceptions that are specific to each technology.

What are the exceptions thrown by the Spring DAO classes ?
Spring DAO classes throw exceptions which are subclasses of DataAccessException(org.springframework.dao.DataAccessException).Spring provides a convenient translation from technology-specific exceptions like SQLException to its own exception class hierarchy with the DataAccessException as the root exception. These exceptions wrap the original exception.
What is SQLExceptionTranslator ?
SQLExceptionTranslator, is an interface to be implemented by classes that can translate between SQLExceptions and Spring's own data-access-strategy-agnostic org.springframework.dao.DataAccessException.
SQLExceptionTranslator, is an interface to be implemented by classes that can translate between SQLExceptions and Spring's own data-access-strategy-agnostic org.springframework.dao.DataAccessException.
What is Spring's JdbcTemplate ?
Spring's JdbcTemplate is central class to interact with a database through JDBC. JdbcTemplate 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.
JdbcTemplate template = new JdbcTemplate(myDataSource);
Spring's JdbcTemplate is central class to interact with a database through JDBC. JdbcTemplate 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.
JdbcTemplate template = new JdbcTemplate(myDataSource);
What is PreparedStatementCreator ?
PreparedStatementCreator:
PreparedStatementCreator:
- Is one of the most common used interfaces for writing data to database.
- Has one method – createPreparedStatement(Connection)
- Responsible for creating a PreparedStatement.
- Does not need to handle SQLExceptions.
What are ORM’s Spring supports ?
Spring supports the following ORM’s :
Spring supports the following ORM’s :
- Hibernate
- iBatis
- JPA (Java Persistence API)
- TopLink
- JDO (Java Data Objects)
- OJB
What are the ways to access Hibernate using Spring ?
There are two approaches to Spring’s Hibernate integration:
There are two approaches to Spring’s Hibernate integration:
- Inversion of Control with a HibernateTemplate and Callback
- Extending HibernateDaoSupport and Applying an AOP Interceptor
24. How to integrate Spring and Hibernate using HibernateDaoSupport?
Spring and Hibernate can integrate using Spring’s SessionFactory called LocalSessionFactory. The integration process is of 3 steps.
Spring and Hibernate can integrate using Spring’s SessionFactory called LocalSessionFactory. The integration process is of 3 steps.
- Configure the Hibernate SessionFactory
- Extend your DAO Implementation from HibernateDaoSupport
- Wire in Transaction Support with AOP
What are the various transaction manager implementations in Spring ?
1. DataSourceTransactionManager : PlatformTransactionManager implementation for single JDBC data sources.
2. HibernateTransactionManager: PlatformTransactionManager implementation for single Hibernate session factories.
3. JdoTransactionManager : PlatformTransactionManager implementation for single JDO persistence manager factories.
4. JtaTransactionManager : PlatformTransactionManager implementation for JTA, i.e. J2EE container transactions.
2. HibernateTransactionManager: PlatformTransactionManager implementation for single Hibernate session factories.
3. JdoTransactionManager : PlatformTransactionManager implementation for single JDO persistence manager factories.
4. JtaTransactionManager : PlatformTransactionManager implementation for JTA, i.e. J2EE container transactions.
No comments:
Post a Comment