spring_dao

40
1

Upload: pendekanti-surendra-kumar

Post on 18-Feb-2016

219 views

Category:

Documents


1 download

DESCRIPTION

Spring_DAO

TRANSCRIPT

Page 1: Spring_DAO

1

Page 2: Spring_DAO

2

Page 3: Spring_DAO

3

Page 4: Spring_DAO

JdbcTemplate:

HibernateTemplate:

Spring also provides:

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

4

Page 5: Spring_DAO

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.)

5

Page 6: Spring_DAO

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.

6

Page 7: Spring_DAO

7

Page 8: Spring_DAO

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/jdbc.properties"/>

</bean>

8

Page 9: Spring_DAO

9

Page 10: Spring_DAO

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: http://static.springsource.org/spring/docs/2.0.x/api/org/springframework/jdbc/core/JdbcTemplate.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;

Field | Type 10

Page 11: Spring_DAO

11

Page 12: Spring_DAO

• 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 : ");

}

}

12

Page 13: Spring_DAO

•Refer: http://static.springsource.org/spring/docs/2.0.x/reference/jdbc.html

for more information on SimpleJdbcTemplate and ParameterizedRowMapper to take advantage of Java 5 language features.

13

Page 14: Spring_DAO

14

Page 15: Spring_DAO

15

Page 16: Spring_DAO

16

Page 17: Spring_DAO

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>

</beans>17

Page 18: Spring_DAO

Since Annotation configuration is enabled in spring configuration file using : <context:annotation-config />

LocalSessionFactoryBean is injected into AccountDaoHibernateImpl using @Autowiredannotation.

Instantiate HiberntateTemplate using wired LocalSessionFactoryBean.

18

Page 19: Spring_DAO

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

19

Page 20: Spring_DAO

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”).list();

}

}

20

Page 21: Spring_DAO

21

Page 22: Spring_DAO

22

Page 23: Spring_DAO

23

Page 24: Spring_DAO

24

Page 25: Spring_DAO

25

Page 26: Spring_DAO

26

Page 27: Spring_DAO

27

Page 28: Spring_DAO

28

Page 29: Spring_DAO

29

Page 30: Spring_DAO

30

Page 31: Spring_DAO

31

Page 32: Spring_DAO

32

Page 33: Spring_DAO

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

33

Page 34: Spring_DAO

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.

34

Page 35: Spring_DAO

PlatformTransactionManager bean definition for Hibernate will look like:

<bean id="myTxManager“ 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"/>

35

Page 36: Spring_DAO

36

Page 37: Spring_DAO

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.

37

Page 38: Spring_DAO

38

Page 39: Spring_DAO

39

Page 40: Spring_DAO

40