Issuu on Google+






Spring also provides: JpaDaoSupport : super class for JPA data access objects. Requires a EntityManagerFactory to be provided; in turn, this class provides a JpaTemplate instance initialized from the supplied EntityManagerFactory to subclasses


Spring Exception hierarchy allows one to handle most persistence exceptions, which are non-recoverable, only in the appropriate layers, without having annoying boilerplate catch-and-throw blocks and exception declarations in one's DAOs. (One can still trap and handle exceptions anywhere one needs to though.)


The Spring Framework takes care of all the low-level details that can make JDBC such a tedious API to develop with. Application developer just need to specify the appropriate Statement to execute and process the results.



In Spring 1.x the same can be achieved as listed: <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:com/mindtree/dao/"/> </bean>



The update() method of JdbcTemplate can be used for inserting/updating/deleting operations. public int update(String sql, Object[] args, int[] argTypes) throws DataAccessException Parameters: sql - SQL containing bind parameters args - arguments to bind to the query argTypes - SQL types of the arguments (constants from java.sql.Types) Returns: the number of rows affected Refer: dbcTemplate.html For the complete list of overloded update() methods.

For DDL statements, execute() method of JdbcTemplate can be used. Example: jdbcTemplate.execute("create table Account(ACCOUNT_NO varchar(25), ACCOUNT_OWNER varchar(100), BALANCE double)"); Sql> desc account;



For every row that results from the query, JdbcTemplate will call the mapRow() method of the RowMapper.

Within RowMapper, we’ve to write the code that creates a entity object and populate it with values from the ResultSet.

Extracting a list of entities: public List<Account> getAllAccounts() throws DaoException { String sql = "select ACCOUNT_NO,ACCOUNT_OWNER, BALANCE from ACCOUNT"; try { return jdbcTemplate.query(sql, accountRowMapper); } catch (DataAccessException e) { throw new DaoException("Unable to get Accounts : "); } }


â&#x20AC;˘Refer: for more information on SimpleJdbcTemplate and ParameterizedRowMapper to take advantage of Java 5 language features.





LocalSessionFactoryBean can be configured as without using hibernate.cfg.xml: <beans> <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value=“org.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306"/> <property name="username" value=“root"/> <property name="password" value=“root"/> </bean> <bean id="mySessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref="myDataSource"/> <property name="mappingResources"> <list> <value>com/mindtree/entity/Account.hbm.xml</value> <value>com/mindtree/entity/Transaction.hbm.xml</value> </list> </property> <property name="hibernateProperties"> <value> hibernate.dialect=org.hibernate.dialect.MySQLDialect hibernate.show_sql=true </value> </property> </bean>


Since Annotation configuration is enabled in spring configuration file using : <context:annotation-config /> LocalSessionFactoryBean is injected into AccountDaoHibernateImpl using @Autowired annotation. Instantiate HiberntateTemplate using wired LocalSessionFactoryBean.


The HibernateTemplate class provides methods that mirror the methods exposed on the Hibernate Session interface.


You can also use Hibernate Session retrieved using injected SessionFactory without using HibernateTemplate: public class AccountDaoHibernateImpl implements AccountDao { private SessionFactory sessionFactory;

public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } public Collection getAllAccounts() { return this.sessionFactory.getCurrentSession() .createQuery("from Accountâ&#x20AC;?).list(); } }














Other Propagations available are: Propagation MANDATORY: This attribute means that the bean method must always be made part of the transaction scope of the calling client. If the calling client or bean is not part of a transaction, the invocation will fail, throwing a TransactionRequiredException.

Propagation NEVER: This attribute means that the bean method must never be invoked within the scope of a transaction. If the calling client or bean is part of a transaction, the invoked bean which is marked with Propagation.NEVER will throw a Exception. If, however, the calling client or bean is not involved in a transaction, the invoked bean which is marked with Propagation.NEVER will execute normally without a transaction Propagation NESTED: PROPAGATION_NESTED is different again in that it uses a single physical transaction with multiple savepoints that it can roll back to. Such partial rollbacks allow an inner transaction scope to trigger a rollback for its scope, with the outer transaction being able to continue the physical transaction despite some operations having been rolled back. This is typically mapped onto JDBC savepoints, so will only work with JDBC resource transactions


A transaction strategy is defined by the org.springframework.transaction.PlatformTransactionManager interface The TransactionDefinition interface specifies: Isolation: the degree of isolation this transaction has from the work of other transactions.

Propagation: normally all code executed within a transaction scope will run in that transaction. However, there are several options specifying behavior if a transactional method is executed when a transaction context already exists Timeout: how long this transaction may run before timing out (and automatically being rolled back by the underlying transaction infrastructure). Read-only status: a read-only transaction does not modify any data.


PlatformTransactionManager bean definition for Hibernate will look like: <bean id="myTxManagerâ&#x20AC;&#x153; class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="mySessionFactory" /> </bean>

PlatformTransactionManager bean definition for JDBC will look like: <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> PlatformTransactionManager bean definition for JTA will look like: <bean id="txManager" class="org.springframework.transaction.jta.JtaTransactionManager"/>



1)Transactions are applied to all methods of classes present in com.mindtree.dao package. 2) Methods starting with “update” are configured with propagation=“REQUIRED” , other attributes are default isolation level, rollback-rules are not mentioned and hence default rules are applied. By default Transaction rolls back for any Unchecked exception. Checked exceptions that are thrown from a transactional method do not result in rollback in the default configuration

3) Methods starting with “get” are meant for read-only. The update/ insert SQL’s are ignored if any in these methods. Helpful in ORM’s to avoid updates using dirty checking. 4) The default <tx:advice/> settings are: • Propagation setting is REQUIRED. • Isolation level is DEFAULT. • Transaction is read/write. • Transaction timeout defaults to the default timeout of the underlying transaction system, or none if timeouts are not supported. • Any RuntimeException triggers rollback, and any checked Exception does not Note: If the bean id=“transactionManager”, in tx:advice “transaction-manger” attribute is optional.