Using Spring and Hibernate - PowerPoint PPT Presentation

1 / 46
About This Presentation
Title:

Using Spring and Hibernate

Description:

Transaction tx = session.beginTransaction(); Tutor dave=new Tutor('dge','Elliman','Dave' ... No longer need to write a Home interface ... – PowerPoint PPT presentation

Number of Views:574
Avg rating:3.0/5.0
Slides: 47
Provided by: daveel1
Category:

less

Transcript and Presenter's Notes

Title: Using Spring and Hibernate


1
Using Spring and Hibernate
  • Dave Elliman

2
The overall architecture
3
The enterprise view (Java)
4
Revision - What is Dependency Injection?
  • DI is all about wiring up objects or plumbing if
    you prefer
  • It is about ensuring loose coupling and fits well
    with design patterns
  • Design to an interface and then inject the actual
    class at run time
  • This is what inheritence is really for

5
A Real World Example?
Web App
Authenticator
Stock Quotes
Logger
Error Handler
Database
This example was originally created by Jim
Weirich in Ruby on his blog.
6
Remember the old way
  • public class WebApp
  • public WebApp()
  • quotes new StockQuotes()
  • authenticator new Authenticator()
  • database new Database()
  • logger new Logger()
  • errorHandler new ErrorHandler()
  • // More code here...

7
What about the child objects?
  • How does the StockQuotes find the Logger?
  • How does the Authenticator find the database?
  • Suppose you want to use a TestingLogger instead?
    Or a MockDatabase?

8
Service Locator Interface
  • public interface ILocator
  • TObject GetltTObjectgt()

9
Service Locator Example
  • public class MyLocator ILocator
  • protected DictionaryltType, objectgt dict new
    DictionaryltType,objectgt()
  • public MyLocator()
  • dict.Add(typeof(ILogger), new Logger())
  • dict.Add(typeof(IErrorHandler), new
    ErrorHandler(this))
  • dict.Add(typeof(IQuotes), new StockQuotes(this))
  • dict.Add(typeof(IDatabase), new Database(this))
  • dict.Add(typeof(IAuthenticator), new
    Authenticator(this))
  • dict.Add(typeof(WebApp), new WebApp(this))

10
StockQuotes with Locator
  • public class StockQuotes
  • public StockQuotes(ILocator locator)
  • errorHandler locator.GetltIErrorHandlergt()
  • logger locator.GetltILoggergt()
  • // More code here...

11
Good things
  • Classes are decoupled from explicit imlementation
    types
  • Easy to externalise the configuration

12
Dependency Injection Containers
  • Gets rid of the dependency on the ILocator
  • Object is no longer responsible for finding its
    dependencies
  • The container does it for you

13
Then what?
  • Write your objects the way you want
  • Setup the container
  • Ask the container for objects
  • The container creates objects for you and
    fulfills dependencies

14
Setting Up the Container (XML)
  • ltDIContainergt
  • ltTypeMap fromILogger toLogger /gt
  • ltTypeMap fromIDatabase toDatabase /gt
  • ltTypeMap fromIErrorHandler toErrorHandler
    /gt
  • ltTypeMap fromIQuotes toStockQuotes /gt
  • ltTypeMap fromIAuthenticator toAuthenticator
    /gt
  • lt/DIContainergt

15
Creating Objects
  • Test
  • public void WebAppTest()
  • DIContainer container GetContainer()
  • IStockQuotes quotes container.GetltIStockQuotes
    gt()
  • IAuthenticator auth container.GetltIAuthenticat
    orgt()
  • Assert.IsNotNull( quotes.Logger )
  • Assert.IsNotNull( auth.Logger )
  • Assert.AreSame( quotes.Logger, auth.Logger )

16
Existing Frameworks
  • Java
  • Pico Container
  • Spring Framework
  • HiveMind
  • Ruby
  • Rico
  • Copland
  • Python
  • PyContainer
  • .NET
  • Pico.NET
  • Spring.NET
  • pp Object Builder

17
Spring with Persistence Layers
Hibernate?
18
Spring can act as the Application
19
A persistent POJO for Hibernate
  • package elc
  • public class Tutor
  • private String id /// unique identifier
  • private String surname
  • private String firstname
  • private Tutor() /// default constructor
  • public Tutor(String id, String surname,
    String firstname)
  • this.id id this.surname surname
    this.firstname firstname)
  • public String getId() return id
  • public String getSurname() return surname
  • public String getFirstname() return
    firstname
  • public void setId(String id)
    this.id id
  • public void setSurname(String surname)
    this.surname surname
  • public void setLogin(String firstname)
    this.firstname firstname

20
The Hibernate Session
  • import org.hibernate.Session
  • import org.hibernate.SessionFactory
  • import org.hibernate.cfg.Configuration
  • ... some code
  • Session getSessionFactory().openSession()
  • Transaction tx session.beginTransaction()
  • Tutor davenew Tutor("dge","Elliman","Dave")
  • session.save(dave)
  • tx.commit()
  • session.close()
  • ... more code

21
Tutor.hbm.xml
  • lt?xml version'1.0' encoding'utf-8'?gt
  • lt!DOCTYPE hibernate-mapping PUBLIC
  • "-//Hibernate/Hibernate Mapping DTD//EN"
  • "http//hibernate.sourceforge.net/hibernate-ma
    pping-3.0.dtd"gt
  • lthibernate-mappinggt
  • ltclass name"elc.Tutor" table"tutor"gt
  • ltid name"id" type"String" column"ID" gt
  • ltgenerator class"assigned"/gt
  • lt/idgt
  • ltproperty name"firstName"gt
  • ltcolumn name"FIRSTNAME" /gt
  • lt/propertygt
  • ltproperty name"surname"gt
  • ltcolumn name"SURNAME"/gt
  • lt/propertygt
  • lt/classgt
  • lt/hibernate-mappinggt

22
hibernate.cfg.xml
lt?xml version'1.0' encoding'utf-8'?gt lt!DOCTYPE
hibernate-configuration PUBLIC "-//Hibernate/Hiber
nate Configuration DTD//EN" "http//hibernate.sour
ceforge.net/hibernate-configuration-3.0.dtd"gt lthib
ernate-configurationgt ltsession-factorygt
ltproperty name"hibernate.connection.driver_class"
gt com.mysql.jdbc.Driverlt/propertygt
ltproperty name"hibernate.connection.url"gt
jdbcmysql//localhost/hibernatetutoriallt/property
gt ltproperty name"hibernate.connection.usern
ame"gtrootlt/propertygt ltproperty
name"hibernate.connection.password"gtlt/propertygt
ltproperty name"hibernate.connection.pool_siz
e"gt10lt/propertygt ltproperty
name"show_sql"gttruelt/propertygt ltproperty
name"dialect"gtorg.hibernate.dialect.MySQLDialectlt
/propertygt ltproperty name"hibernate.hbm2ddl
.auto"gtupdatelt/propertygt lt!-- Mapping files
--gt ltmapping resource"tutor.hbm.xml"/gt lt/se
ssion-factorygt lt/hibernate-configurationgt
23
Using Hibernate with Spring
  • One simply creates a Hibernate Session Factory
    bean in Spring
  • ltbean idsessionFactory
  • classorg.springframework.orm.hibernate3.LocalSe
    ssio nFactoryBeangt
  • ltproperty nameconfigurationClass
  • value org.bibernate.cfg.Annotation.Configuratio
    n /gt
  • ltproperty nameconfigLocation
    valueclasspathhibernate.cfg.xml /gt
  • lt/beangt

24
An Intereface and a class to define
  • public interface TutorDao
  • public void createTutor(final Tutor tutor)
  • public Tutor getTutor(final String id)
  • Also saveTutor() deleteTutor() etc.
  • CRUD is now done with single lines of code. No
    SQL needed

25
Do you get the CONCEPTS?
  • You can look up the detail when you need it
  • ELC exam will test the concepts and not the
    detail of xml configuration files of Java code
  • You need to know that a configuration file is
    needed and what it does, not the fine detail of
    its formatting

26
Any Questions?
Im confused
27
JEE and EJBs
  • Dave Elliman

28
POJOs and POJIs
  • Plain Old Java Objects and Interfaces
  • In the past EJBs were all rather different and
    special and you could not test them outside a
    container
  • Now they are POJ you can

29
Annotations
  • There has been a revolution in Server-side Java
    and Tiger Jane 1.5 EJB annotations
  • These are processed by a new tool called apt
  • You can write your own if you like

30
Writing EJBs was rather stereotyped
  • An ideal situation for annotations.
  • No longer need to write a Home interface
  • No longer need an XML deployment descriptor
    (deploytool)

31
The Concept
  • Entity bean
  • corresponds to a set of records in a database
  • Session bean
  • handles business flow (one per client unless
    stateless, when may be shared)

32
Enterprise JavaBeans
  • Definition from OReillys Enterprise JavaBeans
    book
  • An Enterprise Java Bean is a standard server-side
    component model
  • Aha! Its a standard for building MIDDLEWARE In
    multi-tiered solutions

33
The Context in Which EJBs Are Used
34
It All Works by RMI
35
A Taxonomy of EJBs
36
Differences Between Beans
  • Entity Beans
  • Represent persistent data
  • Long-lived
  • Session Beans
  • Interact with clients
  • Model business Logic
  • Short-lived

37
Session Bean (Stateful)
  • Assigned to 1 client only
  • Keeps info about a client
  • ie has attributes for clients state
  • Assigned to a client for lifetime
  • Non-persistent
  • Short-lived (client, timeout, server crash)

38
Session Bean (Stateless)
  • Many clients can access it
  • Implements business logic
  • One bean can service multiple clients (fast and
    efficient)
  • Lifetime controlled by container
  • No state across methods
  • Each instance identical upon creation
  • Short-lived

39
Insight Into Session Beans
40
Entity EJBs
  • Bean managed persistence (BMP)
  • developer writes JDBC code and SQL statements
  • Container managed persistence (CMP)
  • Container generates methods to read and write to
    the database dropped!
  • Takes necessary information from the Deployment
    Descriptor

41
EJB Architecture Diagram
42
A Stateless Session Bean
  • import javax.ejb./ A stateless session
    bean requesting that a remote busines
    interface be generated for it./_at_Stateless_at_Remo
    tepublic class HelloWorldBean    public String
    sayHello()       return "Hello World!!!"  

43
A Stateful Session Bean
  • import javax.ejb.
  • _at_Stateful
  • public class ShoppingCartBean implements
    ShoppingCart
  • private String customer
  • public void startToShop(String customer)
    this.customer customer
  • public void addToCart(Item item)
  • System.out.println("Added item to cart... ")
  • _at_Remove
  • public void finishShopping()
  • System.out.println("Shopping Done... ")

44
A Entity Java Bean
  • import javax.ejb.
  • _at_Entity
  • public class Order
  • private Long id
  • private int version
  • private int itemId
  • private int quantity
  • private Customer cust
  • _at_Id(generateAUTO)
  • public Long getId() return id
  • public void setId(Long id) this.id id
  • _at_Version
  • protected int getVersion() return version
  • protected void setVersion(int version)
    this.version version
  • _at_Basic
  • public int getItemId() return itemId

45
SQL and Entity beans
  • Queries can be defined through the _at_NamedQuery
    annotation
  • _at_NamedQuery (name"findACustomers",queryString"
    SELECT c FROM Customer c WHERE c.name LIKE
    custName")

46
End of detour into Java!
Any Questions?
Write a Comment
User Comments (0)
About PowerShow.com