SlideShare a Scribd company logo
SPRING IOC AND DAO By   	       Anusha. Adlux Consultancy Services Pvt. Ltd.
AGENDA Spring IOC Spring DAO ,[object Object]
 HibernateAdlux Consultancy Services Pvt. Ltd.
What is Spring ? The Spring Framework is an open source application framework for the Java platform. ,[object Object], 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.
Benefits of spring ,[object Object]
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 – “don’t 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) ,[object Object],           Direct instantiation 		  Asking a Factory for an implementation ,[object Object], 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. ,[object Object],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.  ,[object Object]
Dependencies are “injected” by container during runtime.
Beans define their dependencies through constructor arguments or propertiesWhy is Dependency Injection better? ,[object Object]
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(); BookDemoDaodao = 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 BookDemoDaodao;     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(BookDemoDaodao) { 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 ,[object Object]
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
XMLBeanFactoryis for implementationBeanFactorybeanFactory = new XmlBeanFactory(new   ClassPathResource( “beans.xml" ) ); MyBeanmyBean = (MyBean) beanFactory.getBean( ”myBean” ); Adlux Consultancy Services Pvt. Ltd.
ApplicationContext ,[object Object]
ApplicationContextextends 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:ApplicationContextcontext = new ClassPathXmlApplicationContext                                                                    (Beans.xml”); MyBeanmyBean = (MyBean) context.getBean( ”myBean” ); Adlux Consultancy Services Pvt. Ltd.
Bean ,[object Object]
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 programmaticallyScopes 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                        <bean id=“bean1” class=“Example” scope=“singleton”/>     prototype :          A new bean instance will be created for each request          Use prototype scope for stateful beans – singleton scope for stateless   beans                      <bean id=“bean1” class=“Example” scope=“prototype”/> 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 BankingAccountImpl{ // the BankingAccountImpl has a dependency on a BankDao              Private BankDaobankDao;           // a constructor so that the Spring container can 'inject' a BankDao               public BankingAccountImpl(BankDaobankDao) {                  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 <beans>     <bean id=“bankdao” class=“BankAccountDao”/>     <bean name=“bankingAccount"                                      class=“BankingAccountImpl">            <constructor-arg>                  <ref  local=“bankdao”/>           </constructor-arg>     </bean>    <bean id=“employeeRegister"             class="examples.EmployeeRegister">           <property name=“employee">                <bean class=“examples.Employee”/>         </property>     </bean> </beans> No Argument constructor bean Constructor Injection. Setter Injection Adlux Consultancy Services Pvt. Ltd.
Autowiring Properties Beans may be auto-wired (rather than using <ref>) 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.
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 DAO’s 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.
Spring’s 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.
Data Access 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 Adlux Consultancy Services Pvt. Ltd.
Consistent Abstract Classes for DAO Support ,[object Object]
JdbcDaoSupport
Super class for JDBC data access objects.

More Related Content

What's hot

Spring Boot - Uma app do 0 a Web em 30 minutos
Spring Boot - Uma app do 0 a Web em 30 minutosSpring Boot - Uma app do 0 a Web em 30 minutos
Spring Boot - Uma app do 0 a Web em 30 minutos
phelypploch
 
Hibernate
HibernateHibernate
Hibernate
Ajay K
 
Project Lombok!
Project Lombok!Project Lombok!
Project Lombok!
Mehdi Haryani
 
Java EE vs Spring Framework
Java  EE vs Spring Framework Java  EE vs Spring Framework
Java EE vs Spring Framework
Rohit Kelapure
 
Domain Driven Design Demonstrated
Domain Driven Design Demonstrated Domain Driven Design Demonstrated
Domain Driven Design Demonstrated
Alan Christensen
 
Lecture 8 Enterprise Java Beans (EJB)
Lecture 8  Enterprise Java Beans (EJB)Lecture 8  Enterprise Java Beans (EJB)
Lecture 8 Enterprise Java Beans (EJB)
Fahad Golra
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot Introduction
Jeevesh Pandey
 
Java Spring Framework
Java Spring FrameworkJava Spring Framework
Java Spring Framework
Mehul Jariwala
 
An introduction to React.js
An introduction to React.jsAn introduction to React.js
An introduction to React.js
Emanuele DelBono
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
Aaron Schram
 
Spring Framework
Spring Framework  Spring Framework
Spring Framework
tola99
 
Top 30 Node.js interview questions
Top 30 Node.js interview questionsTop 30 Node.js interview questions
Top 30 Node.js interview questions
techievarsity
 
Java
JavaJava
Microservices pattern language (microxchg microxchg2016)
Microservices pattern language (microxchg microxchg2016)Microservices pattern language (microxchg microxchg2016)
Microservices pattern language (microxchg microxchg2016)
Chris Richardson
 
React JS - A quick introduction tutorial
React JS - A quick introduction tutorialReact JS - A quick introduction tutorial
React JS - A quick introduction tutorial
Mohammed Fazuluddin
 
Spring Boot in Action
Spring Boot in Action Spring Boot in Action
Spring Boot in Action
Alex Movila
 
Introduction to spring boot
Introduction to spring bootIntroduction to spring boot
Introduction to spring boot
Santosh Kumar Kar
 
Migrating .NET Application to .NET Core
Migrating .NET Application to .NET CoreMigrating .NET Application to .NET Core
Migrating .NET Application to .NET Core
Baris Ceviz
 
What Is Express JS?
What Is Express JS?What Is Express JS?
What Is Express JS?
Simplilearn
 

What's hot (20)

Spring Boot - Uma app do 0 a Web em 30 minutos
Spring Boot - Uma app do 0 a Web em 30 minutosSpring Boot - Uma app do 0 a Web em 30 minutos
Spring Boot - Uma app do 0 a Web em 30 minutos
 
Hibernate
HibernateHibernate
Hibernate
 
Project Lombok!
Project Lombok!Project Lombok!
Project Lombok!
 
Java EE vs Spring Framework
Java  EE vs Spring Framework Java  EE vs Spring Framework
Java EE vs Spring Framework
 
Domain Driven Design Demonstrated
Domain Driven Design Demonstrated Domain Driven Design Demonstrated
Domain Driven Design Demonstrated
 
Lecture 8 Enterprise Java Beans (EJB)
Lecture 8  Enterprise Java Beans (EJB)Lecture 8  Enterprise Java Beans (EJB)
Lecture 8 Enterprise Java Beans (EJB)
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot Introduction
 
Java Spring Framework
Java Spring FrameworkJava Spring Framework
Java Spring Framework
 
An introduction to React.js
An introduction to React.jsAn introduction to React.js
An introduction to React.js
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
 
Spring Framework
Spring Framework  Spring Framework
Spring Framework
 
Top 30 Node.js interview questions
Top 30 Node.js interview questionsTop 30 Node.js interview questions
Top 30 Node.js interview questions
 
Java
JavaJava
Java
 
Microservices pattern language (microxchg microxchg2016)
Microservices pattern language (microxchg microxchg2016)Microservices pattern language (microxchg microxchg2016)
Microservices pattern language (microxchg microxchg2016)
 
React JS - A quick introduction tutorial
React JS - A quick introduction tutorialReact JS - A quick introduction tutorial
React JS - A quick introduction tutorial
 
Spring Boot in Action
Spring Boot in Action Spring Boot in Action
Spring Boot in Action
 
Spring Batch 2.0
Spring Batch 2.0Spring Batch 2.0
Spring Batch 2.0
 
Introduction to spring boot
Introduction to spring bootIntroduction to spring boot
Introduction to spring boot
 
Migrating .NET Application to .NET Core
Migrating .NET Application to .NET CoreMigrating .NET Application to .NET Core
Migrating .NET Application to .NET Core
 
What Is Express JS?
What Is Express JS?What Is Express JS?
What Is Express JS?
 

Viewers also liked

Cassandra Community Webinar | Cassandra 2.0 - Better, Faster, Stronger
Cassandra Community Webinar | Cassandra 2.0 - Better, Faster, StrongerCassandra Community Webinar | Cassandra 2.0 - Better, Faster, Stronger
Cassandra Community Webinar | Cassandra 2.0 - Better, Faster, Stronger
DataStax
 
How Twitter Works (Arsen Kostenko Technology Stream)
How Twitter Works (Arsen Kostenko Technology Stream) How Twitter Works (Arsen Kostenko Technology Stream)
How Twitter Works (Arsen Kostenko Technology Stream)
IT Arena
 
Hash table
Hash tableHash table
Hash table
Rajendran
 
Spring MVC to iOS and the REST
Spring MVC to iOS and the RESTSpring MVC to iOS and the REST
Spring MVC to iOS and the REST
Roy Clarkson
 
Dependency Injection and Inversion Of Control
Dependency Injection and Inversion Of ControlDependency Injection and Inversion Of Control
Dependency Injection and Inversion Of Control
Simone Busoli
 
Metrics at Scale @ UBER (Mantas Klasavicius Technology Stream)
Metrics at Scale @ UBER (Mantas Klasavicius Technology Stream)Metrics at Scale @ UBER (Mantas Klasavicius Technology Stream)
Metrics at Scale @ UBER (Mantas Klasavicius Technology Stream)
IT Arena
 
Inversion of Control - Introduction and Best Practice
Inversion of Control - Introduction and Best PracticeInversion of Control - Introduction and Best Practice
Inversion of Control - Introduction and Best Practice
Lars-Erik Kindblad
 
Amazon interview questions
Amazon interview questionsAmazon interview questions
Amazon interview questions
Sumit Arora
 
System analysis and design
System analysis and design System analysis and design
System analysis and design Razan Al Ryalat
 
Introduction to Graph Databases
Introduction to Graph DatabasesIntroduction to Graph Databases
Introduction to Graph Databases
Max De Marzi
 
System Design and Analysis 1
System Design and Analysis 1System Design and Analysis 1
System Design and Analysis 1Boeun Tim
 
Neo4j - 5 cool graph examples
Neo4j - 5 cool graph examplesNeo4j - 5 cool graph examples
Neo4j - 5 cool graph examplesPeter Neubauer
 
Graph database Use Cases
Graph database Use CasesGraph database Use Cases
Graph database Use Cases
Max De Marzi
 
System Analysis and Design
System Analysis and DesignSystem Analysis and Design
System Analysis and Design
Aamir Abbas
 
Data Modeling with Neo4j
Data Modeling with Neo4jData Modeling with Neo4j
Data Modeling with Neo4j
Neo4j
 

Viewers also liked (16)

Hash map
Hash mapHash map
Hash map
 
Cassandra Community Webinar | Cassandra 2.0 - Better, Faster, Stronger
Cassandra Community Webinar | Cassandra 2.0 - Better, Faster, StrongerCassandra Community Webinar | Cassandra 2.0 - Better, Faster, Stronger
Cassandra Community Webinar | Cassandra 2.0 - Better, Faster, Stronger
 
How Twitter Works (Arsen Kostenko Technology Stream)
How Twitter Works (Arsen Kostenko Technology Stream) How Twitter Works (Arsen Kostenko Technology Stream)
How Twitter Works (Arsen Kostenko Technology Stream)
 
Hash table
Hash tableHash table
Hash table
 
Spring MVC to iOS and the REST
Spring MVC to iOS and the RESTSpring MVC to iOS and the REST
Spring MVC to iOS and the REST
 
Dependency Injection and Inversion Of Control
Dependency Injection and Inversion Of ControlDependency Injection and Inversion Of Control
Dependency Injection and Inversion Of Control
 
Metrics at Scale @ UBER (Mantas Klasavicius Technology Stream)
Metrics at Scale @ UBER (Mantas Klasavicius Technology Stream)Metrics at Scale @ UBER (Mantas Klasavicius Technology Stream)
Metrics at Scale @ UBER (Mantas Klasavicius Technology Stream)
 
Inversion of Control - Introduction and Best Practice
Inversion of Control - Introduction and Best PracticeInversion of Control - Introduction and Best Practice
Inversion of Control - Introduction and Best Practice
 
Amazon interview questions
Amazon interview questionsAmazon interview questions
Amazon interview questions
 
System analysis and design
System analysis and design System analysis and design
System analysis and design
 
Introduction to Graph Databases
Introduction to Graph DatabasesIntroduction to Graph Databases
Introduction to Graph Databases
 
System Design and Analysis 1
System Design and Analysis 1System Design and Analysis 1
System Design and Analysis 1
 
Neo4j - 5 cool graph examples
Neo4j - 5 cool graph examplesNeo4j - 5 cool graph examples
Neo4j - 5 cool graph examples
 
Graph database Use Cases
Graph database Use CasesGraph database Use Cases
Graph database Use Cases
 
System Analysis and Design
System Analysis and DesignSystem Analysis and Design
System Analysis and Design
 
Data Modeling with Neo4j
Data Modeling with Neo4jData Modeling with Neo4j
Data Modeling with Neo4j
 

Similar to Spring IOC and DAO

The Spring Framework: A brief introduction to Inversion of Control
The Spring Framework:A brief introduction toInversion of ControlThe Spring Framework:A brief introduction toInversion of Control
The Spring Framework: A brief introduction to Inversion of ControlVisualBee.com
 
Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans
Hitesh-Java
 
Session 43 - Spring - Part 1 - IoC DI Beans
Session 43 - Spring - Part 1 - IoC DI BeansSession 43 - Spring - Part 1 - IoC DI Beans
Session 43 - Spring - Part 1 - IoC DI Beans
PawanMM
 
Spring training
Spring trainingSpring training
Spring training
TechFerry
 
Spring framework
Spring frameworkSpring framework
Spring frameworkAjit Koti
 
Spring User Guide
Spring User GuideSpring User Guide
Spring User Guide
Muthuselvam RS
 
Spring framework
Spring frameworkSpring framework
Spring framework
Rajkumar Singh
 
2-0. Spring ecosytem.pdf
2-0. Spring ecosytem.pdf2-0. Spring ecosytem.pdf
2-0. Spring ecosytem.pdf
DeoDuaNaoHet
 
Spring session
Spring sessionSpring session
Spring session
Gamal Shaban
 
Spring from a to Z
Spring from  a to ZSpring from  a to Z
Spring from a to Z
sang nguyen
 
Spring io c
Spring io cSpring io c
Spring io cwinclass
 
Spring Framework
Spring FrameworkSpring Framework
Spring Framework
NexThoughts Technologies
 
Spring Basics
Spring BasicsSpring Basics
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
Rajind Ruparathna
 
Spring (1)
Spring (1)Spring (1)
Spring (1)
Aneega
 
Spring IOC
Spring IOCSpring IOC
Spring IOC
SNEHAL MASNE
 
Spring framework
Spring frameworkSpring framework
Spring framework
Sonal Poddar
 
Introduction to Spring sec1.pptx
Introduction to Spring sec1.pptxIntroduction to Spring sec1.pptx
Introduction to Spring sec1.pptx
NourhanTarek23
 
Spring Fa Qs
Spring Fa QsSpring Fa Qs
Spring Fa Qsjbashask
 

Similar to Spring IOC and DAO (20)

The Spring Framework: A brief introduction to Inversion of Control
The Spring Framework:A brief introduction toInversion of ControlThe Spring Framework:A brief introduction toInversion of Control
The Spring Framework: A brief introduction to Inversion of Control
 
Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans
 
Session 43 - Spring - Part 1 - IoC DI Beans
Session 43 - Spring - Part 1 - IoC DI BeansSession 43 - Spring - Part 1 - IoC DI Beans
Session 43 - Spring - Part 1 - IoC DI Beans
 
Spring training
Spring trainingSpring training
Spring training
 
Spring framework
Spring frameworkSpring framework
Spring framework
 
Spring User Guide
Spring User GuideSpring User Guide
Spring User Guide
 
Spring framework
Spring frameworkSpring framework
Spring framework
 
2-0. Spring ecosytem.pdf
2-0. Spring ecosytem.pdf2-0. Spring ecosytem.pdf
2-0. Spring ecosytem.pdf
 
Spring session
Spring sessionSpring session
Spring session
 
Spring from a to Z
Spring from  a to ZSpring from  a to Z
Spring from a to Z
 
Spring io c
Spring io cSpring io c
Spring io c
 
Spring Framework
Spring FrameworkSpring Framework
Spring Framework
 
Spring Basics
Spring BasicsSpring Basics
Spring Basics
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Spring (1)
Spring (1)Spring (1)
Spring (1)
 
Spring IOC
Spring IOCSpring IOC
Spring IOC
 
Spring framework
Spring frameworkSpring framework
Spring framework
 
Introduction to Spring sec1.pptx
Introduction to Spring sec1.pptxIntroduction to Spring sec1.pptx
Introduction to Spring sec1.pptx
 
Spring Fa Qs
Spring Fa QsSpring Fa Qs
Spring Fa Qs
 
Spring 2
Spring 2Spring 2
Spring 2
 

Recently uploaded

Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
g2nightmarescribd
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 

Recently uploaded (20)

Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 

Spring IOC and DAO

  • 1. SPRING IOC AND DAO By Anusha. Adlux Consultancy Services Pvt. Ltd.
  • 2.
  • 3. HibernateAdlux Consultancy Services Pvt. Ltd.
  • 4.
  • 5.
  • 8. JavaBeans loosely coupled through interfaces is a good model.
  • 9. Conversion of checked exceptions to unchecked
  • 11. 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.
  • 12. Spring Architecture Adlux Consultancy Services Pvt. Ltd.
  • 13. 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.
  • 14. 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 – “don’t 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.
  • 15.
  • 16.
  • 17. Dependencies are “injected” by container during runtime.
  • 18.
  • 19. 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.
  • 20. Pull Example public class BookDemoServiceImpl implements BookDemoService { public void addPublisherToBook(Book book) { BookDemoFactory factory = BookDemoFactory.getFactory(); BookDemoDaodao = 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.
  • 21. Push Example (Dependency Injection) public class BookDemoServiceImpl implements BookDemoService { private BookDemoDaodao; 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(BookDemoDaodao) { this.dao = dao; } } Adlux Consultancy Services Pvt. Ltd.
  • 22. 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.
  • 23.
  • 24. Lightweight container that loads bean definitions and manages your beans.
  • 25. Configured declaratively using an XML file, or files, that determine how beans can be referenced and wired together.
  • 26. Knows how to serve and manage a singleton or prototype defined bean
  • 27. Injects dependencies into defined beans when served
  • 28. XMLBeanFactoryis for implementationBeanFactorybeanFactory = new XmlBeanFactory(new ClassPathResource( “beans.xml" ) ); MyBeanmyBean = (MyBean) beanFactory.getBean( ”myBean” ); Adlux Consultancy Services Pvt. Ltd.
  • 29.
  • 31. Adds services such as international messaging capabilities.
  • 32. Add the ability to load file resources in a generic fashion.
  • 33. Provides support for the AOP module.
  • 34. Several ways to configure a context:
  • 36. ClassPathXMLApplicationContext – standalone XML application. Loads a context definition from an XML file located in the class path
  • 37. FileSystemXmlApplicationContext - Loads a context definition from an XML file in file system.
  • 38. Example:ApplicationContextcontext = new ClassPathXmlApplicationContext (Beans.xml”); MyBeanmyBean = (MyBean) context.getBean( ”myBean” ); Adlux Consultancy Services Pvt. Ltd.
  • 39.
  • 40. The bean class is the actual implementation of the bean being described by the BeanFactory.
  • 41. Spring will manage the scope of the beans for you. No need for doing it programmaticallyScopes 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 <bean id=“bean1” class=“Example” scope=“singleton”/> prototype : A new bean instance will be created for each request Use prototype scope for stateful beans – singleton scope for stateless beans <bean id=“bean1” class=“Example” scope=“prototype”/> Adlux Consultancy Services Pvt. Ltd.
  • 42. 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.
  • 43. 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 BankingAccountImpl{ // the BankingAccountImpl has a dependency on a BankDao Private BankDaobankDao; // a constructor so that the Spring container can 'inject' a BankDao public BankingAccountImpl(BankDaobankDao) { this. bankDao = bankDao; } // business logic that actually 'uses' the injected BankDao object } Adlux Consultancy Services Pvt. Ltd.
  • 44. 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.
  • 45. Configuration of the bean in applicationContext.xml <beans> <bean id=“bankdao” class=“BankAccountDao”/> <bean name=“bankingAccount" class=“BankingAccountImpl"> <constructor-arg> <ref local=“bankdao”/> </constructor-arg> </bean> <bean id=“employeeRegister" class="examples.EmployeeRegister"> <property name=“employee"> <bean class=“examples.Employee”/> </property> </bean> </beans> No Argument constructor bean Constructor Injection. Setter Injection Adlux Consultancy Services Pvt. Ltd.
  • 46.
  • 47. Autowiring Properties Beans may be auto-wired (rather than using <ref>) 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.
  • 49. Introduction to spring dao Adlux Consultancy Services Pvt. Ltd.
  • 50. 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.
  • 51. 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 DAO’s 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.
  • 52. Spring’s 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.
  • 53. Data Access 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 Adlux Consultancy Services Pvt. Ltd.
  • 54.
  • 56. Super class for JDBC data access objects.
  • 57. Requires a DataSource to be set, providing a JdbcTemplatebased on it to subclasses.
  • 59. Super class for Hibernate data access objects.
  • 60. Requires a SessionFactory to be set, providing a HibernateTemplatebased on it to subclasses.
  • 62. Super class for JDO data access objects.
  • 63. Requires a PersistenceManagerFactory to be set, providing a JdoTemplatebased on it to subclasses.
  • 65. Supper class for iBATIS SqlMap data access object.
  • 66. Requires a DataSource to be set, providing a SqlMapTemplate.Adlux Consultancy Services Pvt. Ltd.
  • 67. Spring DAO template and Callback classes: Adlux Consultancy Services Pvt. Ltd.
  • 68.
  • 69. ResultSetExtractor interface extracts values from a ResultSet.
  • 72. RowMapperAdlux Consultancy Services Pvt. Ltd.
  • 73. 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.
  • 74. 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.
  • 75. JDBC Template Methods: execute(String sql) : Issue a single SQL execute, typically a DDL statement. execute(CallableStatementCreator csc,CallableStatementCa llback action) : Execute a JDBC data access operation, implemented as callback action working on a JDBC CallableStatement. execute(PrepatedStatementCreator csc,PreparedStatementCa llback action) : Execute a JDBC data access operation, implemented as callback action working on a JDBC PreparedStatement. Adlux Consultancy Services Pvt. Ltd.
  • 76. JDBC Template Methods: query(String sql, Object[] args, int[] argTypes, RowCallbackHandler rch) :          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(String sql, Object[] args, int[] argTypes, RowMapper rowMapper) :          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(String sql, Object[] args) :          Issue a single SQL update operation (such as an insert, update or delete statement) via a prepared statement, binding the given arguments. Adlux Consultancy Services Pvt. Ltd.
  • 77. 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()}); }}
  • 78. Example for a JDBC-based DAO - wiring <beans> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName"> <value>oracle.jdbc.driver.OracleDriver</value> </property> <property name="url"> <value>jdbc:oracle:thin:@192.168.1.99:1521:java</value> </property> <property name="username"> <value>trainee</value> </property> <property name="password"> <value>trainee</value> </property> </bean> <bean id="bankDAO" class="chapter04.dao.BankDaoImpl"> <property name="dataSource"> <ref bean="dataSource"/> </property> </bean> </beans> Adlux Consultancy Services Pvt. Ltd.
  • 79. DATA ACCESS USING ORM IN SPRING Adlux Consultancy Services Pvt. Ltd.
  • 80.
  • 81. But loading all objects would be inefficient
  • 82.
  • 83.
  • 84. cache objects in memory whenever you can
  • 86. Optimistic locking and cache invalidation for changing objectsAdlux Consultancy Services Pvt. Ltd.
  • 87.
  • 90. Thread-safe, lightweight template classes that support Hibernate, JDO, and iBatis SQL Maps.
  • 91. Convenience support classes HibernateDaoSupport, JdoDaoSupport, SqlMapDaoSupportAdlux Consultancy Services Pvt. Ltd.
  • 92.
  • 93.
  • 95.
  • 96.
  • 97. setup of Hibernate SessionFactory
  • 99. implicit management of Hibernate Sessions
  • 101. easily get an instance of a HibernateTemplate using getHibernateTemplate().
  • 102. Also provides many other methods like getSession() , closeSessionIfNecessary() .Adlux Consultancy Services Pvt. Ltd.
  • 103. SessionFactory setup in a Spring container <bean id=“datasource” class="org.springframework.jdbc.datasource.DriverManagerDataSource"> ……………. </bean> <bean id="sessionFactory" class="org.springframework. orm.hibernate.LocalSessionFactoryBean"> <property name="dataSource“> <ref bean="dataSource"/> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect"> org.hibernate.dialect.Oracle9Dialect </prop> </props> </property> <property name="mappingResources"> <property name=“mappingDirectoryLocations”> <list> <list> <value>Student.hbm.xml</value> <value>classpath:/com/adlux/mappings <value>Course.hbm.xml</value> </value> …...… </list> </list> </property> </property> ……….. </bean> Adlux Consultancy Services Pvt. Ltd.
  • 104. Configuring Springs’ Hibernate Template <bean id="hibernateTemplate" class="org.springframework.orm.hibernate.HibernateTemplate"> <property name="sessionFactory"> <ref bean="sessionFactory"/> </property> </bean> <bean id="studentDao" class="com.adlux..dao.hibernate.StudentDaoHibernate"> <property name="hibernateTemplate"> <ref bean="hibernateTemplate"/> </property> </bean> <bean id="courseDao" class="com.adlux. dao.hibernate.CourseDaoHibernate"> <property name="hibernateTemplate"> <ref bean="hibernateTemplate"/> </property> </bean> Configuring a HibernateTemplate class Wiring Template class with multiple DAO objects. Adlux Consultancy Services Pvt. Ltd.
  • 105. Hibernate Template Spring framework provides template class for Hibernate framework, which helps release the programmer from writing some repetitive codes. This template class is called HibernateTemplate. Using HibernateTemplate and HibernateCallback public Student getStudent(final Integer id) { return (Student) hibernateTemplate.execute( new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException { return session.load(Student.class, id); } }); } Adlux Consultancy Services Pvt. Ltd.
  • 106.
  • 107. Hibernate Template Methods hibernate.load(Class entityClass, Serializable id)           Return the persistent instance of the given entity class with the given identifier, throwing an exception if not found. hibernate.save(Object entity)   Persist the given transient instance. hibernate.update(Object entity) Update the given persistent instance, associating it with the current Hibernate Session. Adlux Consultancy Services Pvt. Ltd.
  • 108. Examples Using HibernateTemplate List employees = hibernatetemplate.find("from Credit"); List list = hibernatetemplate.find("from Credit c where c.cardtype=?", “Master card”); Save Credit c = new Credit(5121212121212124, ”Master card”,……); hibernatetemplate.save(c); Load & Update Credit e = (Employee) hibernatetemplate.load(Credit.class, cardno); c.setFirstName(“Anusha"); hibernatetemplate.update(e); Adlux Consultancy Services Pvt. Ltd.
  • 109.
  • 110. Requires a SessionFactory to be set, providing a HibernateTemplate based on it to subclasses.
  • 111. easily get an instance of a HibernateTemplate using getHibernateTemplate().
  • 113. We can make our DAO class extends HibernateDaoSupport instead of injecting the instance of HibernateTemplate to each DAO class.
  • 114. Also provides many other methods like getSession() , closeSessionIfNecessary()Adlux Consultancy Services Pvt. Ltd.
  • 115. Example for Spring Dao extending HibernateDaoSupport public class ExampleHibernateDAO extends HibernateDaoSupport { public void insertEmployee(Employee emp) { getHibernateTemplate().save(emp); } public List getAllEmployees() { return getHibernateTemplate().find("from Employee"); } public List findEmployeebyName(String ename) { return getHibernateTemplate().find("from Employee emp where emp.firstname=?", ename); } public void deleteEmployee(String empid) { getHibernateTemplate().delete(getHibernateTemplate().load( Employee.class, empid)); } public void updateEmployee(String empid) { Employee e = (Employee) getHibernateTemplate().load( Employee.class, empid); e.setFirstname("Anusha"); getHibernateTemplate().update(e); } } Adlux Consultancy Services Pvt. Ltd.
  • 116. WriningsessionFactory to our DAO class <bean id="ExampleDao" class=“com.adlux.dao.ExampleHibernateDao"> <property name="sessionFactory"> <ref bean="sessionFactory"/> </property> </bean> Adlux Consultancy Services Pvt. Ltd.
  • 117. 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.
  • 118. 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.
  • 120. Spring’s DAO exception hierarchy Adlux Consultancy Services Pvt. Ltd.
  • 121. Spring’s DAO exception hierarchy Adlux Consultancy Services Pvt. Ltd.
  • 122. Thank You Adlux Consultancy Services Pvt. Ltd.