Download - Spring IOC and DAO
Slide 1
By
Anusha.
SPRING IOC AND DAO
Adlux Consultancy Services Pvt. Ltd.
AGENDA
Spring IOC
Spring DAO
JDBC
Hibernate
Adlux Consultancy Services Pvt. Ltd.
What is Spring ?
The Spring Framework is an open source application framework for the Java platform.
Spring is a lightweight inversion of control container framework with the support for aspect-oriented programming and provides DAO template support for Hibernate, SQLMaps and JDBC.
Spring 1.0 Released March 2004. The first version was written by Rod Johnson. Current version is 2.5.6.
Adlux Consultancy Services Pvt. Ltd.
3
Benefits of spring
Implements the concept of IOC.
Provides declarative programming without J2EE
Provides support for AOP.
JavaBeans loosely coupled through interfaces is a good model.
Conversion of checked exceptions to unchecked
Extremely modular and flexible
Well designed
Easy to extend
Many reusable classes.
Spring substantially reduces code, speeds up development, facilitates easy testing and improves code quality
Adlux Consultancy Services Pvt. Ltd.
Spring Architecture
Adlux Consultancy Services Pvt. Ltd.
Spring Modules
The Core container module
AOP module (Aspect Oriented Programming)
JDBC abstraction and DAO module
O/R mapping integration module (Object/Relational)
Web module
MVC framework module
Adlux Consultancy Services Pvt. Ltd.
Inversion of Control (IOC)
Instead of objects invoking other objects, the dependant objects are added through an external entity/container.
Inversion of Control is the general style of using Dependency Injection to wire the application.
Also known as the Hollywood principle dont call me I will call you.
IoC is all about Object dependencies.
Prevents hard-coded object creation and object/service lookup.
Loose coupling
Helps write effective unit tests.
Adlux Consultancy Services Pvt. Ltd.
Inversion of Control (IOC)
Traditional "Pull" approach:
Direct instantiation
Asking a Factory for an implementation
"Push" approach:
Something outside of the Object "pushes" its dependencies into it. The Object has no knowledge of how it gets its dependencies, it just assumes they are there.
The "Push" approach is called "Dependency Injection".
Adlux Consultancy Services Pvt. Ltd.
Dependency Injection
Dependency injection is a style of object configuration in which an objects fields and collaborators are set by an external entity.
Dependency Injection is the act of injecting dependencies into an Object.
Dependencies are injected by container during runtime.
Beans define their dependencies through constructor arguments or properties
Why is Dependency Injection better?
Loose Coupling is improved because you don't hard-code dependencies between layers and modules. Instead you configure them outside of the code. This makes it easy to swap in a new implementation of a service, or break off a module and reuse it elsewhere.
Testability is improved because your Objects don't know or care what environment they're in as long as someone injects their dependencies. Hence you can deploy Objects into a test environment and inject Mock Objects for their dependencies with ease.
Adlux Consultancy Services Pvt. Ltd.
Pull Example
public class BookDemoServiceImpl implements BookDemoService {
public void addPublisherToBook(Book book) {
BookDemoFactory factory = BookDemoFactory.getFactory();
BookDemoDao dao = factory.getBookDemoDao();
String isbn = book.getIsbn();
if (book.getPublisher() == null && isbn != null) {
Publisher publisher = dao.findPublisherByIsbn(isbn);
book.setPublisher(publisher);
}
}
}
Adlux Consultancy Services Pvt. Ltd.
Push Example (Dependency Injection)
public class BookDemoServiceImpl implements BookDemoService {
private BookDemoDao dao;
public void addPublisherToBook(Book book) {
String isbn = book.getIsbn();
if (book.getPublisher() == null && isbn != null) {
Publisher publisher = dao.findPublisherByIsbn(isbn);
book.setPublisher(publisher);
}
}
public void setBookDemoDao(BookDemoDao dao) {
this.dao = dao;
}
}
Adlux Consultancy Services Pvt. Ltd.
Spring IOC
The IoC container is the core component of the Spring
Framework
A bean is an object that is managed by the IoC container
The IoC container is responsible for containing and
managing beans
Spring comes with two types of containers
BeanFactory
ApplicationContext
Adlux Consultancy Services Pvt. Ltd.
BeanFactory
BeanFactory is core to the Spring framework
Provides basic support for dependency injection
Lightweight container that loads bean definitions and manages your beans.
Configured declaratively using an XML file, or files, that determine how beans can be referenced and wired together.
Knows how to serve and manage a singleton or prototype defined bean
Injects dependencies into defined beans when served
XMLBeanFactory is for implementation
BeanFactory beanFactory = new XmlBeanFactory(new
ClassPathResource( beans.xml" ) );
MyBean myBean = (MyBean) beanFactory.getBean( myBean );
Adlux Consultancy Services Pvt. Ltd.
ApplicationContext
A Spring ApplicationContext allows you to get access to the objects that are configured in a BeanFactory in a framework manner.
ApplicationContext extends BeanFactory
Adds services such as international messaging capabilities.
Add the ability to load file resources in a generic fashion.
Provides support for the AOP module.
Several ways to configure a context:
XMLWebApplicationContext Configuration for a web application.
ClassPathXMLApplicationContext standalone XML application. Loads a context definition from an XML file located in the class path
FileSystemXmlApplicationContext - Loads a context definition from an XML file in file system.
Example:
ApplicationContext context = new ClassPathXmlApplicationContext
(Beans.xml);
MyBean myBean = (MyBean) context.getBean( myBean );
Adlux Consultancy Services Pvt. Ltd.
Bean
A bean is an object that is managed by the IoC container.
The bean class is the actual implementation of the bean being described by the BeanFactory.
Spring will manage the scope of the beans for you. No need for doing it programmatically
Scopes
singleton :
A single bean definition to a single object instance.
Only one shared instance will ever be created by the container
The single bean instance will be stored in cache and returned for all requests.
Singleton beans are created at container startup-time
Singleton is default scope in Spring
prototype :
A new bean instance will be created for each request
Use prototype scope for stateful beans singleton scope for stateless beans
Adlux Consultancy Services Pvt. Ltd.
request
Scopes a single bean definition to the lifecycle of a single HTTP
request; that is each and every HTTP request will have its own instance
of a bean created off the back of a single bean definition. Only
valid in the context of a Spring ApplicationContext.
session
Scopes a single bean definition to the lifecycle of a HTTP Session. Only
valid in the context of a Spring ApplicationContext.
global session
Scopes a single bean definition to the lifecycle of a global HTTP
Session. Typically only valid when used in a portlet context. Only valid
in the context of a Spring ApplicationContext.
request , session , global session scopes are used for spring web applications.
Adlux Consultancy Services Pvt. Ltd.
Injecting dependencies via constructor
Constructor-based DI is effected by invoking a constructor with a number of arguments, each representing a dependency
Example of a class that could only be dependency injected using constructor injection.
public class BankingAccount Impl{
// the BankingAccount Impl has a dependency on a BankDao
Private BankDao bankDao;
// a constructor so that the Spring container can 'inject' a BankDao
public BankingAccount Impl(BankDao bankDao) {
this. bankDao = bankDao;
}
// business logic that actually 'uses' the injected BankDao object
}
Adlux Consultancy Services Pvt. Ltd.
Injecting dependencies via setter methods
Setter-based DI is realized by calling setter methods on your beans after invoking a no-arugument constructor.
public class EmployeeRegister {
// the EmployeeRegister has a dependency on the Employee
private Employee employee;
// a setter method so that the Spring container can 'inject' Employee
public void setEmployee(Employee employee) {
this.employee = employee;
}
// business logic that actually 'uses' the injected Employee Object
}
Adlux Consultancy Services Pvt. Ltd.
Configuration of the bean in applicationContext.xml
Constructor Injection.
Setter Injection
No Argument constructor bean
Adlux Consultancy Services Pvt. Ltd.
Autowiring Properties
Beans may be auto-wired (rather than using )
Per-bean attribute autowire
Explicit settings override
autowire=name
Bean identifier matches property name
autowire=type
Type matches other defined bean
autowire=constructor
Match constructor argument types
autowire=autodetect
Attempt by constructor, otherwise type
Adlux Consultancy Services Pvt. Ltd.
Adlux Consultancy Services Pvt. Ltd.
Introduction to spring dao
Adlux Consultancy Services Pvt. Ltd.
23
Application Layering
A clear separation of application component responsibility.
- Presentation layer
Concentrates on request/response actions.
Handles UI rendering from a model.
Contains formatting logic and non-business related validation logic.
- Persistence layer
Used to communicate with a persistence store such as a relational database.
Provides a query language
Possible O/R mapping capabilities
JDBC, Hibernate, iBATIS, JDO, Entity Beans, etc.
- Domain layer
Contains business objects that are used across above layers.
Contain complex relationships between other domain objects.
Domain objects should only have dependencies on other domain objects.
Adlux Consultancy Services Pvt. Ltd.
What is DAO:
J2EE developers use the Data Access Object (DAO) design pattern to separate low-level data access logic from high-level business logic. Implementing the DAO pattern involves more than just writing data access code.
DAO stands for data access object, which perfectly describes a DAOs role in an application. DAOs exist to provide a means to read and write data to the database .They should expose this functionality through an interface by which the rest of the application will access them.
Adlux Consultancy Services Pvt. Ltd.
Springs JDBC API:
Why not just use JDBC
Connection management
Exception Handling
Transaction management
Other persistence mechanisms
Spring Provides a Consistent JDBC Abstraction
Spring Helper classes
JdbcTemplate
Dao Implementations
Query and BatchQueries
Adlux Consultancy Services Pvt. Ltd.
Support for DAO implementations
implicit access to resources
many operations become one-liners
no try/catch blocks anymore
Pre-built integration classes
JDBC: JdbcTemplate
Hibernate: HibernateTemplate
JDO: JdoTemplate
TopLink: TopLinkTemplate
iBatis SQL Maps: SqlMapClientTemplate
Data Access
Adlux Consultancy Services Pvt. Ltd.
Consistent Abstract Classes for DAO Support
Extend your DAO classes with the proper xxxDAOSupport class that matches your persistence mechanism.
JdbcDaoSupport
Super class for JDBC data access objects.
Requires a DataSource to be set, providing a JdbcTemplate based on it to subclasses.
HibernateDaoSupport
Super class for Hibernate data access objects.
Requires a SessionFactory to be set, providing a HibernateTemplate based on it to subclasses.
JdoDaoSupport
Super class for JDO data access objects.
Requires a PersistenceManagerFactory to be set, providing a JdoTemplate based on it to subclasses.
SqlMapDaoSupport
Supper class for iBATIS SqlMap data access object.
Requires a DataSource to be set, providing a SqlMapTemplate.
Adlux Consultancy Services Pvt. Ltd.
Spring DAO template and Callback classes:
Adlux Consultancy Services Pvt. Ltd.
JDBC Template:
This is the central class in the JDBC core package. It simplifies the use of JDBC and helps to avoid common errors. It executes core JDBC workflow, leaving application code to provide SQL and extract results. This class executes SQL queries or updates.
Code using this class need only implement callback interfaces
PreparedStatementCreator callback interface creates a prepared statement given a Connection, providing SQL and any necessary parameters.
ResultSetExtractor interface extracts values from a ResultSet.
PreparedStatementSetter
RowCallbackHandler
RowMapper
Adlux Consultancy Services Pvt. Ltd.
Writing Data:
public class InsertAccountStatementCreator
implements PreparedStatementCreator {
public PreparedStatement createPreparedStatement(
Connection conn) throws SQLException {
String sql = "insert into abbas_bank_acc(acc_no, acc_holder_name, balance) values (?, ?, ?)";
return conn.prepareStatement(sql);
}
}
Public class InsertAccountStatementSetter implements PreparedStatementSetter{
public void setValues(PreparedStatement ps) throws SQLException {
ps.setInt(0, account.getAccno());
ps.setString(1, account.getAcc_holder_name());
ps.setString(2, account.getBalance());
}
Adlux Consultancy Services Pvt. Ltd.
Reading Data:
public class BankAccountRowMapper implements RowMapper {
public Object mapRow(ResultSet rs, int index) throws SQLException {
BankAccount account = new BankAccount();
account.setAccno(rs.getInt("acc_no"));
account.setAcc_holder_name(rs.getString("acc_holder_name"));
account.setBalance(rs.getDouble("balance"));
}
return account;
}
public List selectAccounts() {
String sql = "select * from abbas_bank_acc";
return getJdbcTemplate().query(sql, new BankAccountRowMapper());
}
Adlux Consultancy Services Pvt. Ltd.
JDBC Template Methods:
execute(Stringsql) :
Issue a single SQL execute, typically a DDL statement.
execute(CallableStatementCreatorcsc,CallableStatementCa llback action) :
Execute a JDBC data access operation, implemented as callback action working on a JDBC CallableStatement.
execute(PrepatedStatementCreatorcsc,PreparedStatementCa llback action) :
Execute a JDBC data access operation, implemented as callback action working on a JDBC PreparedStatement.
Adlux Consultancy Services Pvt. Ltd.
query(Stringsql, Object[]args, int[]argTypes, RowCallbackHandlerrch) :Query given SQL to create a prepared statement from SQL and a list of arguments to bind to the query, reading the ResultSet on a per-row basis with a RowCallbackHandler.
query(Stringsql, Object[]args, int[]argTypes, RowMapperrowMapper) :Query given SQL to create a prepared statement from SQL and a list of arguments to bind to the query, mapping each row to a Java object via a RowMapper.
update(Stringsql, Object[]args) :Issue a single SQL update operation (such as an insert, update or delete statement) via a prepared statement, binding the given arguments.
JDBC Template Methods:
Adlux Consultancy Services Pvt. Ltd.
Example for a JDBC-based DAO
public class BankDaoImpl extends JdbcDaoSupport implements BankDAO {
public void createAccount(BankAccount account) {
getJdbcTemplate().execute(insert into bank_acc values(+accno+,+name+,+balance+));
}
public void deleteAccount(int accno) {
String sql = "delete from abbas_bank_acc where acc_no=?";
getJdbcTemplate().update(sql,new Object[]{new Integer(accno)});
}
public BankAccount selectAccount(int accno) {
String sql = "select * from bank_acc where acc_no=?";
final BankAccount account = new BankAccount();
getJdbcTemplate().query(sql,new Object[]{accno},new RowCallbackHandler(){
public void processRow(ResultSet rs) throws SQLException {
account.setAccno(rs.getInt("acc_no"));
account.setAcc_holder_name(rs.getString("acc_holder_name"));
account.setBalance(rs.getDouble("balance"));
}
});
return account;
}
public List selectAccounts() {
String sql = "select * from bank_acc";
return getJdbcTemplate().queryForList("select * from bank_acc where accno="+accno);
public void updateAccount(BankAccount account) {
String sql = "update bank_acc set balance=? where acc_no=?";
getJdbcTemplate().update(sql, new Object[]{account.getBalance(),account.getAccno()});
}}
Example for a JDBC-based DAO - wiring
oracle.jdbc.driver.OracleDriver
jdbc:oracle:thin:@192.168.1.99:1521:java
trainee
trainee
Adlux Consultancy Services Pvt. Ltd.
Adlux Consultancy Services Pvt. Ltd.
DATA ACCESS USING ORM
IN SPRING
Adlux COnsultancy Services Pvt. Ltd.
ORM Features
Lazy loading
Provide the illusion that objects are in memory
But loading all objects would be inefficient
load an object when it is first accessed
Eager loading
Loading objects one at a time can be inefficient
Load multiple objects per-select statement
Caching
Database often the performance bottleneck
cache objects in memory whenever you can
Easy for readonly objects
Optimistic locking and cache invalidation for changing objects
Adlux Consultancy Services Pvt. Ltd.
Benefits of using Spring to create your O/R mapping applications
Ease of testing.
General resource management.
Exception wrapping.
Thread-safe, lightweight template classes that support Hibernate, JDO, and iBatis SQL Maps.
Convenience support classes HibernateDaoSupport, JdoDaoSupport, SqlMapDaoSupport
Adlux Consultancy Services Pvt. Ltd.
Spring DAO : Hibernate
Manages Hibernate sessions
No more custom ThreadLocal sessions
Sessions are managed within Spring.
HibernateTemplate makes common operations easy
Simpler, consistent exception handling
Many operations become one-liners
Less, simpler, code compared to using Hibernate alone
Portability: Switch between Hibernate, JDO and other transparent persistence technologies without changing DAO interfaces
Can even switch to JDBC where transparent update is not implied
Mixed use of Hibernate and JDBC within the same application.
Adlux Consultancy Services Pvt. Ltd.
Hibernate in spring
Spring's LocalSessionFactoryBean
setup of Hibernate SessionFactory
Spring's HibernateTemplate
implicit management of Hibernate Sessions
SubClassing HibernateDaoSupport Class
easily get an instance of a HibernateTemplate using getHibernateTemplate().
Also provides many other methods like getSession() , closeSessionIfNecessary() .
Adlux Consultancy Services Pvt. Ltd.
SessionFactory setup in a Spring container
.
Adlux Consultancy Services Pvt. Ltd.
Examples using HibernateTemplate and plain hibernate
Hibernate Only :
public User getUserByEmailAddress(final String email) { try {
Session session =getsessionFactory().openSession(); List list = session.find( "from User user where user.email=+ email+); return (User) list.get(0); }
Catch (Exception e){
e.printstackTrace(); } finally { session.close(); }
}
Hibernate Template :
public User getUserByEmailAddress(final String email) { List list = getHibernateTemplate().find("from User user where user.email=?, email);
return (User) list.get(0);
}
Adlux Consultancy Services Pvt. Ltd.
Consistent exception hierarchy in spring
Spring provides a convenient translation from technology specific exceptions like SQLException and HibernateException to its own exception hierarchy with the DataAccessException as the root exception.
DataAccessException is a RuntimeException, so it is an unchecked exception. Our code will not be required to handle these exceptions when they are thrown by the data access tier.
DataAccessException is the root of all Spring DAO exceptions
Adlux Consultancy Services Pvt. Ltd.
Adlux Consultancy Services Pvt. Ltd.
Springs DAO exception hierarchy
Adlux Consultancy Services Pvt. Ltd.
Adlux COnsultancy Services Pvt. Ltd.
Springs DAO exception hierarchy
Adlux Consultancy Services Pvt. Ltd.
Adlux COnsultancy Services Pvt. Ltd.
Adlux Consultancy Services Pvt. Ltd.
Thank You