SlideShare uma empresa Scribd logo
1 de 56
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.

Mais conteúdo relacionado

Mais procurados

Java Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepJava Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By Step
Guo Albert
 
Presentation on "An Introduction to ReactJS"
Presentation on "An Introduction to ReactJS"Presentation on "An Introduction to ReactJS"
Presentation on "An Introduction to ReactJS"
Flipkart
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentation
guest11106b
 

Mais procurados (20)

Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Spring Boot in Action
Spring Boot in Action Spring Boot in Action
Spring Boot in Action
 
Spring Framework
Spring FrameworkSpring Framework
Spring Framework
 
Java Spring
Java SpringJava Spring
Java Spring
 
Hibernate in Action
Hibernate in ActionHibernate in Action
Hibernate in Action
 
Spring User Guide
Spring User GuideSpring User Guide
Spring User Guide
 
Hibernate architecture
Hibernate architectureHibernate architecture
Hibernate architecture
 
Spring Security 5
Spring Security 5Spring Security 5
Spring Security 5
 
Java Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepJava Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By Step
 
Apache tomcat
Apache tomcatApache tomcat
Apache tomcat
 
Xke spring boot
Xke spring bootXke spring boot
Xke spring boot
 
React JS part 1
React JS part 1React JS part 1
React JS part 1
 
Introduction to React JS for beginners
Introduction to React JS for beginners Introduction to React JS for beginners
Introduction to React JS for beginners
 
ReactJS presentation
ReactJS presentationReactJS presentation
ReactJS presentation
 
Presentation on "An Introduction to ReactJS"
Presentation on "An Introduction to ReactJS"Presentation on "An Introduction to ReactJS"
Presentation on "An Introduction to ReactJS"
 
Spring boot
Spring bootSpring boot
Spring boot
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentation
 
Basics of React Hooks.pptx.pdf
Basics of React Hooks.pptx.pdfBasics of React Hooks.pptx.pdf
Basics of React Hooks.pptx.pdf
 
Web api
Web apiWeb api
Web api
 
react redux.pdf
react redux.pdfreact redux.pdf
react redux.pdf
 

Destaque

System analysis and design
System analysis and design System analysis and design
System analysis and design
Razan Al Ryalat
 
System Design and Analysis 1
System Design and Analysis 1System Design and Analysis 1
System Design and Analysis 1
Boeun Tim
 
Neo4j - 5 cool graph examples
Neo4j - 5 cool graph examplesNeo4j - 5 cool graph examples
Neo4j - 5 cool graph examples
Peter Neubauer
 

Destaque (17)

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)
 
Dependency injection - the right way
Dependency injection - the right wayDependency injection - the right way
Dependency injection - the right way
 
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
 

Semelhante a 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 Control
VisualBee.com
 
Spring framework
Spring frameworkSpring framework
Spring framework
Ajit Koti
 
Spring io c
Spring io cSpring io c
Spring io c
winclass
 
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 Qs
jbashask
 
Spring introduction
Spring introductionSpring introduction
Spring introduction
Lê Hảo
 

Semelhante a 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
 
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 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
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Spring introduction
Spring introductionSpring introduction
Spring introduction
 

Último

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Último (20)

🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 

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.