Hibernate - PowerPoint PPT Presentation

1 / 65
About This Presentation
Title:

Hibernate

Description:

... governs the transformation of data from one representation to the other (and vice versa) ... EventManager mgr = new EventManager ... – PowerPoint PPT presentation

Number of Views:112
Avg rating:3.0/5.0
Slides: 66
Provided by: higg8
Category:

less

Transcript and Presenter's Notes

Title: Hibernate


1
Hibernate
2
Hibernate
  • Hibernate is a powerful, high performance
    object/relational persistence and query service.
    Hibernate lets you develop persistent classes
    following object-oriented idiom - including
    association, inheritance, polymorphism,
    composition, and collections. Hibernate allows
    you to express queries in its own portable SQL
    extension (HQL), as well as in native SQL, or
    with an object-oriented Criteria and Example API.
  • Unlike many other persistence solutions,
    Hibernate does not hide the power of SQL from you
    and guarantees that your investment in relational
    technology and knowledge is as valid as always.
    The LGPL open source license allows the use of
    Hibernate and NHibernate in open source and
    commercial projects.

3
Java Persistence with Hibernate
  • The Java Persistence API is the standard
    object/relational mapping and persistence
    management interface of the Java EE 5.0 platform.
    As part of the EJB 3.0 specification effort, it
    is supported by all major vendors of the Java
    industry.
  • Hibernate implements the Java Persistence
    object/relational mapping and persistence
    management interfaces with the Hibernate
    Annotations and Hibernate EntityManager modules,
    on top of the mature and powerful Hibernate Core.
  • The Hibernate modules can be stacked and combined
    as desired. You can use the Hibernate Java
    Persistence provider in any environment, Java SE
    5.0 or Java EE 5.0. The Hibernate Java
    Persistence provider is fully certified and
    passes the Sun TCK.

4
Hibernate Annotations
  • Project Lead Emmanuel BernardLatest release
    3.4.0 GA (Changelog) (Road Map)Release date
    20.08.2008Requirements Hibernate Core 3.3.x, JDK
    5.0Hibernate, like all other object/relational
    mapping tools, requires metadata that governs the
    transformation of data from one representation to
    the other (and vice versa). As an option, you can
    now use JDK 5.0 annotations for object/relational
    mapping with Hibernate 3.2. You can use
    annotations in addition to or as a replacement of
    XML mapping metadata.
  • The Hibernate Annotations package includes
  • Standardized Java Persistence and EJB 3.0 (JSR
    220) object/relational mapping annotations
  • Hibernate-specific extension annotations for
    performance optimization and special mappings
  • You can use Hibernate extension annotations on
    top of standardized Java Persistence annotations
    to utilize all native Hibernate features.

5
More jar file downloads
  • You will need persistence and ejb jar files ejb,
    persistence, jndi, geronimo-ejb, ejb3-persistence
    and javaee.
  • Hibernate tutorials
  • http//www.hibernate.org/hib_docs/reference/en/htm
    l/tutorial.html
  • http//www.roseindia.net/hibernate/index.shtml
  • http//www.hibernate.org/hib_docs/reference/en/htm
    l/tutorial-webapp.html
  • http//www.inf.ed.ac.uk/teaching/courses/ec/handou
    ts/quickstart.pdf

6
Hibernate tutorials
  • I hope to put two or three tutorials here. Right
    now there is just one, an application program
    running against a mysql db, with just one table,
    using hibernate.
  • Hibernate standardizes the db interface. A config
    file specifies the actual db service and the
    dialect to use, and other config files, called
    hbm, map the individual tables. Instead of
    provider-specific connection and query details,
    the program uses the hibernate interface to
    interact with the database.

7
First hibernate tutorial
  • Using hibernate with a mysql database and a few
    simple java classes.
  • Link for tutorial http//www.hibernate.org/hib_do
    cs/reference/en/html/tutorial-firstapp.html
  • This tutorial has many omissions, most notably
    library jar files needed, also a few errors or
    typos about where files go. I also had to modify
    some classes (HibernateUtil) somewhat to get it
    to work.

8
ant
  • Youll use ant and a build file appears in the
    next slide. If you change directories or file
    names youll have to make modifications in the
    ant script.
  • Recall, ant must be in the system path and all
    your java stuff must be in the path/classpath for
    the ant build to work.
  • Note, the build requires directories called src,
    bin and lib. Contents are detailed later.

9
build.xml
  • ltproject name"hibernate-tutorial"
    default"compile"gt
  • ltproperty name"sourcedir" value"basedir/s
    rc"/gt
  • ltproperty name"targetdir" value"basedir/b
    in"/gt
  • ltproperty name"librarydir"
    value"basedir/lib"/gt
  • ltpath id"libraries"gt
  • ltfileset dir"librarydir"gt
  • ltinclude name".jar"/gt
  • lt/filesetgt
  • lt/pathgt
  • lttarget name"clean"gt
  • ltdelete dir"targetdir"/gt
  • ltmkdir dir"targetdir"/gt
  • lt/targetgt
  • lttarget name"compile" depends"clean,
    copy-resources"gt
  • ltjavac srcdir"sourcedir"
  • destdir"targetdir"
  • classpathref"libraries"/gt
  • lt/targetgt
  • lttarget name"copy-resources"gt

10
Notes about lib directory
  • Youll need the following jars
  • hibernate
  • cp30
  • antlr
  • jta
  • dom4j
  • commons logging and collections
  • Just 2 files from slf4j(simple and api)note
    screen shot!!!
  • You wont need hsqldb thats another db service
    connector, but you will need the mysql-java db
    connector

11
My lib directory
12
Directory structure
  • Your_App_dir
  • bin
  • src
  • log4j.properties
  • hibernate.cfg.xml
  • Event.hbm.xml
  • hibernate.properties --- not included in this
    example
  • events(dir)
  • Event.java
  • util(dir)
  • EventManager.java
  • HibernateUtil.java
  • Lib (see previous slide)

13
HibernateUtil.java
  • package util
  • //you can find this class in eclipse, netbeans or
    online, with few variations
  • import org.hibernate.
  • import org.hibernate.cfg.
  • public class HibernateUtil
  • private static final SessionFactory
    sessionFactory
  • static
  • try
  • System.out.println("in try for build session
    factory")
  • // Create the SessionFactory from
    hibernate.cfg.xml
  • sessionFactory new
    Configuration().configure().buildSessionFactory()
  • System.out.println("back from build
    session factory")
  • catch (Throwable ex)
  • // Make sure you log the exception,
    as it might be swallowed
  • System.err.println("Initial
    SessionFactory creation failed." ex)
  • System.out.println("Initial
    SessionFactory creation failed." ex)
  • throw new ExceptionInInitializerError(
    ex)
  • public static SessionFactory
    getSessionFactory()

14
EventManager.java entirety also in slide notes
  • package events
  • import org.hibernate.
  • import org.hibernate.cfg.
  • import java.util.Date
  • import java.util.
  • import util.HibernateUtil
  • public class EventManager
  • public static void main(String args)
    //main
  • EventManager mgr new EventManager()
  • System.out.println("Event Manager before if")
    /////I stuck in all these
    println
  • if (args0.equals("store")) //if
  • System.out.println("create and store")
  • mgr.createAndStoreEvent("My Event", new
    Date())
  • //if
  • else if (args0.equals("list"))
  • System.out.println("list events")
  • List events mgr.listEvents()
  • for (int i 0 i lt events.size() i)

15
EventManager.java continued
  • private List listEvents()
  • System.out.println("Event Manager... in list
    events method")
  • SessionFactory sessionFactory
    HibernateUtil.getSessionFactory()
  • Session session sessionFactory.openSession()
  • session.beginTransaction()
  • List result session.createQuery("from
    Event").list()
  • session.getTransaction().commit()
  • return result
  • private void createAndStoreEvent(String
    title, Date theDate)
  • System.out.println("Event Manager... create and
    store method")
  • SessionFactory sessionFactory
    HibernateUtil.getSessionFactory()
  • Session session sessionFactory.openSession(
    )
  • System.out.println(".. before begin
    transaction")
  • session.beginTransaction()
  • System.out.println(".. transaction started")
  • Event theEvent new Event()
  • theEvent.setTitle(title)

16
Event.java
  • package events
  • import java.util.Date
  • public class Event
  • private Long id
  • private String title
  • private Date date
  • public Event()
  • public Long getId()
  • return id
  • private void setId(Long id)
  • this.id id
  • public Date getDate()
  • return date
  • public void setDate(Date date)
  • this.date date

17
Event.hbm.xml --such a file (and the
corresponding java class) is needed for each
table mapped.
  • lt?xml version"1.0"?gt
  • lt!DOCTYPE hibernate-mapping PUBLIC
  • "-//Hibernate/Hibernate Mapping DTD
    3.0//EN"
  • "http//hibernate.sourceforge.net/hibernat
    e-mapping-3.0.dtd"gt
  • lthibernate-mappinggt
  • ltclass name"events.Event" table"EVENTS"gt
  • ltid name"id" column"EVENT_ID"gt
  • ltgenerator class"native"/gt
  • lt/idgt
  • ltproperty name"date" type"timestamp"
    column"EVENT_DATE"/gt
  • ltproperty name"title"/gt
  • lt/classgt
  • lt/hibernate-mappinggt

18
hibernate.cfg.xml contains connection info, db
name, user name pw and other information
  • lt?xml version'1.0' encoding'utf-8'?gt
  • lt!DOCTYPE hibernate-configuration PUBLIC
  • "-//Hibernate/Hibernate Configuration DTD
    3.0//EN"
  • "http//hibernate.sourceforge.net/hibernate-config
    uration-3.0.dtd"gt
  • lthibernate-configurationgt
  • ltsession-factorygt
  • lt!-- Database connection settings --gt
  • ltproperty name"connection.driver_class"gtcom.mysql
    .jdbc.Driverlt/propertygt
  • ltproperty name"connection.url"gtjdbcmysql//local
    host/mydblt/propertygt
  • ltproperty name"connection.username"gtrootlt/propert
    ygt
  • ltproperty name"connection.password"gtlt/propertygt
  • lt!-- JDBC connection pool (use the built-in) --gt
  • ltproperty name"hibernate.connection.pool_size"
    gt10lt/propertygt
  • lt!-- MySQL dialect//different for different
    Database --gt
  • ltproperty name"dialect"gtorg.hibernate.dialect.MyS
    QLDialectlt/propertygt
  • lt!-- Echo all executed SQL to stdout --gt
  • ltproperty name"show_sql"gttruelt/propertygt
  • ltproperty name"hbm2ddl.auto"gtupdatelt/propertygt
  • ltmapping resource"Event.hbm.xml"/gt

19
Log4j.properties
  • log4j.appender.stdoutorg.apache.log4j.ConsoleAppe
    nder
  • log4j.appender.stdout.TargetSystem.out
  • log4j.appender.stdout.layoutorg.apache.log4j.Patt
    ernLayout
  • log4j.appender.stdout.layout.ConversionPatternd
    ABSOLUTE 5p c1L - mn
  • log4j.rootLoggerinfo, stdout
  • log4j.logger.org.hibernate.testinfo
  • log4j.logger.org.hibernate.tool.hbm2ddldebug

20
remark
  • Youll need to create a mysql database and table
    for this example and you need to start the
    database server before running the example.
  • Run the example in the root directory on the
    commandline either with
  • ant run Dactionstore
  • Or
  • ant run Dactionlist

21
black screen output for store (when it works)
  • C\hibernateexamplegtant run -Dactionstore
  • Buildfile build.xml
  • clean
  • delete Deleting directory C\hibernateexample
    \bin
  • mkdir Created dir C\hibernateexample\bin
  • copy-resources
  • copy Copying 6 files to C\hibernateexample
    \bin
  • copy Copied 2 empty directories to 1 empty
    directory under C\hibernateex
  • ample\bin
  • compile
  • javac Compiling 3 source files to
    C\hibernateexample\bin
  • run
  • java Event Manager before if
  • java create and store
  • java Event Manager... create and store
    method
  • java in try for build session factory
  • ltltltomitted a lotsee slide notesgtgtgt
  • java 719 main INFO
    org.hibernate.tool.hbm2ddl.SchemaUpdate - schema
    upd
  • ate complete

22
Run list when it worksentirety in notes
  • C\hibernateexamplegtant run -Dactionlist
  • Buildfile build.xml
  • clean
  • copy-resources
  • compile
  • javac Compiling 3 source files to
    C\hibernateexample\bin
  • run
  • ltltleft out a lot of output heregtgtgtgt
  • java 531 main INFO
    org.hibernate.impl.SessionFactoryImpl - building
    ses
  • sion factory
  • java 719 main INFO org.hibernate.impl.Ses
    sionFactoryObjectFactory - Not
  • binding factory to JNDI, no JNDI name configured
  • java 719 main INFO org.hibernate.tool.hbm
    2ddl.SchemaUpdate - Running hb
  • m2ddl schema update
  • java 719 main INFO org.hibernate.tool.hbm
    2ddl.SchemaUpdate - fetching d
  • atabase metadata
  • java 719 main INFO org.hibernate.tool.hbm
    2ddl.SchemaUpdate - updating s

23
Your project
24
notes
  • First, of course, get the original tutorial
    working.
  • Modify the EventManager so it opens a JFrame with
    two button, list and store, a textfield and a
    textarea.
  • You are welcome to make a different table but you
    dont have to.
  • (E.C. You may want another button to delete
    from db/table)
  • List button will display stored events in a
    textarea.
  • Store button will get data for the event from a
    textfield.
  • E.C. The tutorial code uses a timestamp, but
    maybe something else like a string with MM/DD/YY
    format would be nicer.

25
So whats the point of hibernate?
  • A uniform connection (that session thingy) and
    sql dialect in your object. This doesnt change
    as you port your application.
  • The hibernate.cfg.xml (NOT your java code) gets
    modified if you port your app, or change database
    servers.

26
The hibernate webapp
27
WEB-INF\web.xml
  • lt?xml version"1.0" encoding"UTF-8"?gt
  • ltweb-app version"2.4"
  • xmlns"http//java.sun.com/xml/ns/j2ee"
  • xmlnsxsi"http//www.w3.org/2001/XMLSchema-in
    stance"
  • xsischemaLocation"http//java.sun.com/xml/ns
    /j2ee http//java.sun.com/xml/ns/j2ee/web-app_2_4.
    xsd"gt
  • ltservletgt
  • ltservlet-namegtEvent Managerlt/servlet-namegt
  • ltservlet-classgtevents.EventManagerServletlt
    /servlet-classgt
  • lt/servletgt
  • ltservlet-mappinggt
  • ltservlet-namegtEvent Managerlt/servlet-namegt
  • lturl-patterngt/eventmanagerlt/url-patterngt
  • lt/servlet-mappinggt
  • lt/web-appgt

28
Where do files go? Shown in another slide but
note
  • Hibernate.cfg goes in classes dir
  • Event.hbm.xml goes into Events dir (I think)

29
The 1-table hibernate web app
  •     http//www.hibernate.org/hib_docs/reference/en
    /html/tutorial-webapp.html
  • This tutorial came from hibernate.org. I think it
    is basically correct, although I made changes to
    the servlet trying to fix unrelated problems. I
    also used my own HibernateUtil class (shown in
    previous tutorial).
  • Not very many details about the directory
    structure were given in the tutorial, but I give
    them here.

30
Servlet running in tomcat
31
Servlet entirety in slide notes
  • package events
  • import java.io.
  • import java.net.
  • import java.text.SimpleDateFormat
  • import java.util.Date
  • import java.util.Iterator
  • import java.util.List
  • import javax.servlet.
  • import javax.servlet.http.
  • import util.HibernateUtil
  • import org.hibernate.
  • public class EventManagerServlet extends
    HttpServlet
  • SessionFactory sessionFactory
  • Session session

32
Servlet continued
  • protected void processRequest(HttpServletRequest
    request, HttpServletResponse response)
  • throws ServletException, IOException
  • response.setContentType("text/htmlcharset
    UTF-8")
  • SimpleDateFormat dateFormatter new
    SimpleDateFormat("dd.MM.yyyy")
  • PrintWriter out response.getWriter()
  • out.println("lthtmlgtltheadgtlttitlegtEvent
    Managerlt/titlegtlt/headgtltbodygt")
  • try
  • // Begin unit of work
  • // HibernateUtil.getSessionFactory().ge
    tCurrentSession().beginTransaction()
  • sessionFactory HibernateUtil.getSess
    ionFactory()
  • session sessionFactory.openSession()
  • session.beginTransaction()
  • // Handle actions
  • if ("store".equals(request.getParamete
    r("action")))
  • String eventTitle
    request.getParameter("eventTitle")
  • String eventDate
    request.getParameter("eventDate")
  • if ("".equals(eventTitle)
    "".equals(eventDate))
  • out.println("ltbgtltigtPlease
    enter event title and date.lt/igtlt/bgt")

33
Servlet continued
  • private void printEventForm(PrintWriter out)
  • out.println("lth2gtAdd new eventlt/h2gt")
  • out.println("ltformgt")
  • out.println("Title ltinput
    name'eventTitle' length'50'/gtltbr/gt")
  • out.println("Date (e.g. 24.12.2009)
    ltinput name'eventDate' length'10'/gtltbr/gt")
  • out.println("ltinput type'submit'
    name'action' value'store'/gt")
  • out.println("lt/formgt")
  • private void listEvents(PrintWriter out,
    SimpleDateFormat dateFormatter)
  • List result HibernateUtil.getSessionFact
    ory().getCurrentSession().createCriteria(Event.cla
    ss).list()
  • if (result.size() gt 0)
  • out.println("lth2gtEvents in
    databaselt/h2gt")
  • out.println("lttable border'1'gt")
  • out.println("lttrgt")
  • out.println("ltthgtEvent titlelt/thgt")
  • out.println("ltthgtEvent datelt/thgt")

34
Servlet continued
  • protected void createAndStoreEvent(String title,
    Date theDate)
  • Event theEvent new Event()
  • theEvent.setTitle(title)
  • theEvent.setDate(theDate)
  • HibernateUtil.getSessionFactory().getCurre
    ntSession().save(theEvent)
  • protected void doGet(HttpServletRequest
    request, HttpServletResponse response)
  • throws ServletException, IOException
  • processRequest(request, response)
  • protected void doPost(HttpServletRequest
    request, HttpServletResponse response)
  • throws ServletException, IOException
  • processRequest(request, response)

35
One line added to cfg
  • lt?xml version'1.0' encoding'utf-8'?gt
  • lt!DOCTYPE hibernate-configuration PUBLIC
  • "-//Hibernate/Hibernate Configuration DTD
    3.0//EN"
  • "http//hibernate.sourceforge.net/hibernate-config
    uration-3.0.dtd"gt
  • lthibernate-configurationgt
  • ltsession-factorygt
  • lt!-- Database connection settings --gt
  • ltproperty name"connection.driver_class"gtcom.mysql
    .jdbc.Driverlt/propertygt
  • ltproperty name"connection.url"gtjdbcmysql//local
    host/mydblt/propertygt
  • ltproperty name"connection.username"gtrootlt/propert
    ygt
  • ltproperty name"connection.password"gtlt/propertygt
  • lt!-- JDBC connection pool (use the built-in) --gt
  • ltproperty name"hibernate.connection.pool_size"
    gt10lt/propertygt
  • lt!-- MySQL dialect//different for different
    Database --gt
  • ltproperty name"dialect"gtorg.hibernate.dialect.MyS
    QLDialectlt/propertygt
  • lt!-- Echo all executed SQL to stdout --gt
  • ltproperty name"show_sql"gttruelt/propertygt
  • ltproperty name"hbm2ddl.auto"gtupdatelt/propertygt
  • ltproperty name"current_session_context_class"gtthr
    eadlt/propertygt

36
This build puts webapp war file one directory up
(like in C)
  • ltproject name"hibernate-tutorial"
    default"compile"gt
  • ltproperty name"sourcedir" value"basedir/s
    rc"/gt
  • ltproperty name"targetdir" value"basedir/b
    in"/gt
  • ltproperty name"librarydir"
    value"basedir/lib"/gt
  • ltpath id"libraries"gt
  • ltfileset dir"librarydir"gt
  • ltinclude name".jar"/gt
  • lt/filesetgt
  • lt/pathgt
  • lttarget name"clean"gt
  • ltdelete dir"targetdir"/gt
  • ltmkdir dir"targetdir"/gt
  • lt/targetgt
  • lttarget name"compile" depends"clean,
    copy-resources"gt
  • ltjavac srcdir"sourcedir"
  • destdir"targetdir"
  • classpathref"libraries"/gt
  • lt/targetgt
  • lttarget name"copy-resources"gt

37
Package things in WEB-INF as shown here
  • WEB-INF
  • classes (dir)
  • events(dir)
  • Event.class (no changes to this file)
  • EventManagerServlet.class
  • Event.hbm.xml (no changes to this file)
  • util(dir)
  • HibernateUtil.class (this file same as in
    previous project)
  • Hibernate.cfg.xml (shown above one line added)
  • If it cant find tableclass.hbm.xml then put them
    here
  • lib(dir) (no changes to this)
  • log4j.properties(no changes to this)
  • web.xml (shown above)

38
Jar
  • I used jar instead of ant build
  • jar cvf appname.war WEB-INF
  • Creates a jar called appname.war from contents of
    WEB-INF
  • Youll need to move files and directories as per
    earlier slide before creating a war file.

39
Whats next?
  • I will put a 2nd hibernate project here to be
    assigned after the hibernate desktop app. I
    havent finished working on it, but it will
    likely involve CRUD against a database using one
    or more servlets, like your servlet database
    project, except use a hibernate interface.

40
Two examples multiple tables crud
  • documentation http//www.hibernate.org/hib_docs/re
    ference/en/html/

41
(No Transcript)
42
Adding to tables listing
  • I modified previous example, adding a people
    table and displaying contents of two tables.
  • I did not do a select, I just printed the event
    title in the same position. But since the
    numbers are allocated sequentially, I could have
    used select title from Event where idnumber

43
My tables
  • My People table and my Event table both have ids
    as primary key, autoincremented.
  • In the hbm, these are identified as

44
Dir structure
  • WEB-INF
  • log4j.properties
  • web.xml
  • lib (contents shown later)
  • classes
  • hibernate.cfg.xml
  • util
  • Same HibernateUtil.java as previous
  • events
  • Same Event.java as previous
  • People.java
  • EventManagerServlet.java
  • People.hbm.xml
  • Event.hbm.xml (unchanged from prev example)

45
some of these may be unnecessary but I whittled
it down some
46
Entire Servlet in notes
  • package events
  • import java.io.
  • import java.net.
  • import java.text.SimpleDateFormat
  • import java.util.Date
  • import java.util.Iterator
  • import java.util.List
  • import javax.servlet.
  • import javax.servlet.http.
  • import util.HibernateUtil
  • import org.hibernate.
  • public class EventManagerServlet extends
    HttpServlet
  • SessionFactory sessionFactory
  • List result1,result2
  • Session session
  • protected void processRequest(HttpServletReque
    st request, HttpServletResponse response)
  • throws ServletException, IOException
  • response.setContentType("text/htmlcharset
    UTF-8")

47
Servletprint form, get session
  • // Handle actions
  • if ("store".equals(request.getParameter
    ("action")))
  • String eventTitle
    request.getParameter("eventTitle")
  • String eventDate
    request.getParameter("eventDate")
  • String name request.getParameter("name")
  • String phone request.getParameter("phone")
  • if ("".equals(eventTitle)
    "".equals(eventDate)name.equals("")phone.equal
    s(""))
  • out.println("ltbgtltigtPlease
    enter person, event title and date.lt/igtlt/bgt")
  • else
  • System.out.println("before call to create
    and store")
  • createAndStoreEvent(name,
    phone,eventTitle, dateFormatter.parse(eventDate))
  • out.println("ltbgtltigtAdded
    event.lt/igtlt/bgt")
  • // Print page

48
Servlet the form and table of events
  • private void printEventForm(PrintWriter out)
  • out.println("lth2gtAdd new eventlt/h2gt")
  • out.println("ltformgt")
  • out.println("Title ltinput
    name'eventTitle' length'50'/gtltbr/gt")
  • out.println("Date (e.g. 24.12.2009)
    ltinput name'eventDate' length'10'/gtltbr/gt")
  • out.println("Contact person ltinput
    name'name' length'50'/gtltbr/gt")
  • out.println("Phone(e.g. (123) 432-1111
    ltinput name'phone' length'50'/gtltbr/gt")
  • out.println("ltinput type'submit'
    name'action' value'store'/gt")
  • out.println("lt/formgt")
  • private void listEvents(PrintWriter out,
    SimpleDateFormat dateFormatter)
  • result1 session.createCriteria(Event.class).l
    ist()
  • if (result1.size() gt 0)
  • out.println("lth2gtEvent Info in
    databaselt/h2gt")
  • out.println("lttable border'1'gt")
  • out.println("lttrgt")

49
Servlet list table of people
  • int num0
  • result2 session.createCriteria(People.clas
    s).list()
  • if (result2.size() gt 0)
  • out.println("lth2gtPeople Info in
    databaselt/h2gt")
  • out.println("lttable border'1'gt")
  • out.println("lttrgt")
  • out.println("ltthgtPersonlt/thgt")
  • out.println("ltthgtPhonelt/thgt")
  • out.println("ltthgtEvent
    coordinatinglt/thgt")
  • out.println("lt/trgt")
  • String unknown"unknown"
  • for (Iterator it
    result2.iterator() it.hasNext())
  • People person(People)it.next()
  • out.println("lttrgt")
  • out.println("lttdgt"
    person.getName() "lt/tdgt")
  • out.println("lttdgt"
    person.getPhone() "lt/tdgt")
  • out.println("lttdgt" ((Event)result1.get(num)).get
    Title() "lt/tdgt")
  • num

50
Create and store
  • protected void createAndStoreEvent(String
    name,String phone,String title, Date theDate)
  • System.out.println("in create and store
    method")
  • Event theEvent new Event()
  • People personnew People()
  • theEvent.setTitle(title)
  • theEvent.setDate(theDate)
  • person.setName(name)
  • person.setPhone(phone)
  • System.out.println("about to get current
    session and save event")
  • session.save(theEvent)
  • System.out.println("about to get current
    session and save person")
  • session.save(person)
  • System.out.println("done with saves")
  • protected void doGet(HttpServletRequest
    request, HttpServletResponse response)
  • throws ServletException, IOException
  • System.out.println("in do get")

51
events.People.java
  • public class People
  • private String name
  • private String phone
  • private long id
  • public People()
  • public long getId()return id
  • public void setId(long id)this.idid
  • public String getName()
  • return name
  • public void setName(String name)
  • this.name name
  • public String getPhone()

52
The primary key may be generated, native or
assigned. The strategy must be specified in the
hbm.xml. This is People.hbm.xml
  • lt?xml version"1.0"?gt
  • lt!DOCTYPE hibernate-mapping PUBLIC
  • "-//Hibernate/Hibernate Mapping DTD
    3.0//EN"
  • "http//hibernate.sourceforge.net/hibernat
    e-mapping-3.0.dtd"gt
  • lthibernate-mappinggt
  • ltclass name"events.People" table"people"gt
  • ltid name"id" column"id"gt
  • ltgenerator class"native"/gt
  • lt/idgt
  • ltproperty name"name"/gt
  • ltproperty name"phone"/gt
  • lt/classgt
  • lt/hibernate-mappinggt

53
Same hibernate.cfg.xml except People table has
been added.
  • lt?xml version'1.0' encoding'utf-8'?gt
  • lt!DOCTYPE hibernate-configuration PUBLIC
  • "-//Hibernate/Hibernate Configuration DTD
    3.0//EN"
  • "http//hibernate.sourceforge.net/hibernate-config
    uration-3.0.dtd"gt
  • lthibernate-configurationgt
  • ltsession-factorygt
  • lt!-- Database connection settings --gt
  • ltproperty name"connection.driver_class"gtcom.mysql
    .jdbc.Driverlt/propertygt
  • ltproperty name"connection.url"gtjdbcmysql//local
    host/mydblt/propertygt
  • ltproperty name"connection.username"gtrootlt/propert
    ygt
  • ltproperty name"connection.password"gtlt/propertygt
  • lt!-- JDBC connection pool (use the built-in) --gt
  • ltproperty name"hibernate.connection.pool_size"
    gt10lt/propertygt
  • lt!-- MySQL dialect//different for different
    Database --gt
  • ltproperty name"dialect"gtorg.hibernate.dialect.MyS
    QLDialectlt/propertygt
  • ltproperty name"cache.provider_class"gtorg.hibernat
    e.cache.NoCacheProviderlt/propertygt
  • lt!-- Echo all executed SQL to stdout --gt
  • lt!-- Echo all executed SQL to stdout --gt
  • ltproperty name"show_sql"gttruelt/propertygt

54
ant build still needs to be modified to build
WEB-INF and classes dirs, and copy files to
there, then jar
  • ltproject name"hibernate-tutorial"
    default"compile"gt
  • ltproperty name"sourcedir" value"basedir/s
    rc"/gt
  • ltproperty name"targetdir" value"basedir/b
    in"/gt
  • ltproperty name"librarydir"
    value"basedir/lib"/gt
  • ltpath id"libraries"gt
  • ltfileset dir"librarydir"gt
  • ltinclude name".jar"/gt
  • lt/filesetgt
  • lt/pathgt
  • lttarget name"clean"gt
  • ltdelete dir"targetdir"/gt
  • ltmkdir dir"targetdir"/gt
  • lt/targetgt
  • lttarget name"compile" depends"clean,
    copy-resources"gt
  • ltjavac srcdir"sourcedir"
  • destdir"targetdir"
  • classpathref"libraries"/gt
  • lt/targetgt
  • lttarget name"copy-resources"gt

55
CRUD example
  • The student table

56
Hibernate student info servlet
57
remarks
  • Just one table marked
  • Link above gives good information on how to
    conduct queries.
  • I used radiobuttons to indicate function desired.
  • I used the same ant/build and jar commands as
    before.
  • Same directory structure.
  • Servlet in slide notes

58
Student.hbm.xml
  • lt?xml version"1.0"?gt
  • lt!DOCTYPE hibernate-mapping PUBLIC
  • "-//Hibernate/Hibernate Mapping DTD
    3.0//EN"
  • "http//hibernate.sourceforge.net/hibernat
    e-mapping-3.0.dtd"gt
  • lthibernate-mappinggt
  • ltclass name"data.Student" table"Students"gt
  • ltid name"id" column"id"gt
  • ltgenerator class"native"/gt
  • lt/idgt
  • ltproperty name"name"/gt
  • ltproperty name"age"/gt
  • ltproperty name"gpa"/gt
  • ltproperty name"sex"/gt
  • ltproperty name"year"/gt
  • lt/classgt

59
Some bits of the servlet
  • try
  • // Begin unit of work
  • // HibernateUtil.getSessionFactory().ge
    tCurrentSession().beginTransaction()
  • sessionFactory HibernateUtil.getSess
    ionFactory()
  • session sessionFactory.openSession()
  • session.beginTransaction()
  • if ("store".equals(request.getParameter
    ("action")))
  • String name request.getParameter
    ("name")
  • String gpa request.getParameter(
    "gpa")
  • String year request.getParameter("year")
  • String age request.getParameter("age")
  • String sex request.getParameter("sex")
  • if ("".equals(name)
    "".equals(sex)year.equals("")gpa.equals("")a
    ge.equals(""))
  • out.println("ltbgtltigtPlease
    enter name, age, sex, gpa, year and
    sex.lt/igtlt/bgt")
  • else
  • System.out.println("before call to create and
    store")
  • createAndStoreEvent(name,
    age,year,sex,gpa)
  • out.println("ltbgtltigtAdded
    event.lt/igtlt/bgt")
  • else if ("list".equals(request.getParam
    eter("action")))

60
Delete action
  • else if ("delete".equals(request.getParameter("ac
    tion")))
  • String name request.getParameter("name")
  • List markedsession.createQuery("from Student as
    student where student.name?").setString(0,name).l
    ist()
  • if(marked.size()gt0)
  • Student student(Student)marked.get(0)
  • out.println("deleting...." student.getName())
  • session.delete(student)
  • else out.println("no match found")

61
  • else//update
  • String name request.getParameter("name")
  • String gpa request.getParameter("g
    pa")
  • String year request.getParameter("year")
  • String age request.getParameter("age")
  • String sex request.getParameter("sex")
  • List markedsession.createQuery("from Student as
    student where student.name?").setString(0,name).l
    ist()
  • if(marked.size()gt0!"".equals(sex)!year.equal
    s("")!gpa.equals("")!age.equals(""))
  • Student student(Student)marked.get(0)
  • student.setAge(Integer.parseInt(age))
  • student.setYear(year)
  • student.setGpa(Double.parseDouble(gpa))
  • student.setSex(sex)
  • session.update(student)
  • else out.println("no match found")
  • /else a getinfo choice could look about the
    same

62
I used radiobuttons
  • private void printStudentForm(PrintWriter out)
  • out.println("lth2gtStudent info
    formlt/h2gt")
  • out.println("ltformgt")
  • out.println("Name ltinput name'name'
    length'40'/gtltbr/gt")
  • out.println("Age ltinput name'age'
    length'10'/gtltbr/gt")
  • out.println("Sex(Male/Female) ltinput
    name'sex' length'10'/gtltbr/gt")
  • out.println("Year ltinput name'year'
    length'15'/gtltbr/gt")
  • out.println("GPA ltinput name'gpa'
    length'10'/gtltbr/gt")
  • out.println("ltinput type'radio'
    name'action' value'list'gt Listltbrgt")
  • out.println(" ltinput type'radio'
    name'action' value'store' checkedgt Storeltbrgt")
  • out.println("ltinput type'radio'
    name'action' value'update'gt Updateltbrgt")
  • out.println(" ltinput type'radio'
    name'action' value'delete'gt Deleteltbrgt")
  • out.println("ltinput type'submit' /gt")
  • out.println("lt/formgt")

63
List students
  • private void listStudents(PrintWriter out)
  • result1 session.createCriteria(Student.class)
    .list()
  • if (result1.size() gt 0)
  • out.println("lth2gtStudent
    Infolt/h2gt")
  • out.println("lttable border'1'gt")
  • out.println("lttrgt")
  • out.println("ltthgtStudent namelt/thgt")
  • out.println("ltthgtStudent Agelt/thgt")
  • out.println("ltthgtGPAlt/thgt")
  • out.println("ltthgtSexlt/thgt")
  • out.println("ltthgtYearlt/thgt")
  • out.println("lt/trgt")
  • for (Iterator it result1.iterator()
    it.hasNext())
  • Student student (Student)
    it.next()
  • out.println("lttrgt")

64
Hibernate configuration
  • lt?xml version'1.0' encoding'utf-8'?gt
  • lt!DOCTYPE hibernate-configuration PUBLIC
  • "-//Hibernate/Hibernate Configuration DTD
    3.0//EN"
  • "http//hibernate.sourceforge.net/hibernate-config
    uration-3.0.dtd"gt
  • lthibernate-configurationgt
  • ltsession-factorygt
  • lt!-- Database connection settings --gt
  • ltproperty name"connection.driver_class"gtcom.mysql
    .jdbc.Driverlt/propertygt
  • ltproperty name"connection.url"gtjdbcmysql//local
    host/mydblt/propertygt
  • ltproperty name"connection.username"gtrootlt/propert
    ygt
  • ltproperty name"connection.password"gtlt/propertygt
  • lt!-- JDBC connection pool (use the built-in) --gt
  • ltproperty name"hibernate.connection.pool_size"
    gt10lt/propertygt
  • lt!-- MySQL dialect//different for different
    Database --gt
  • ltproperty name"dialect"gtorg.hibernate.dialect.MyS
    QLDialectlt/propertygt
  • lt!-- Echo all executed SQL to stdout --gt
  • ltproperty name"show_sql"gttruelt/propertygt
  • ltproperty name"hbm2ddl.auto"gtupdatelt/propertygt
  • ltmapping resource"Student.hbm.xml"/gt

65
web-xml
  • lt?xml version"1.0" encoding"UTF-8"?gt
  • ltweb-app version"2.4"
  • xmlns"http//java.sun.com/xml/ns/j2ee"
  • xmlnsxsi"http//www.w3.org/2001/XMLSchema-in
    stance"
  • xsischemaLocation"http//java.sun.com/xml/ns
    /j2ee http//java.sun.com/xml/ns/j2ee/web-app_2_4.
    xsd"gt
  • ltservletgt
  • ltservlet-namegtStudentInfolt/servlet-namegt
  • ltservlet-classgtdata.StudentInfoServletlt/se
    rvlet-classgt
  • lt/servletgt
  • ltservlet-mappinggt
  • ltservlet-namegtStudentInfolt/servlet-namegt
  • lturl-patterngt/studentinfolt/url-patterngt
  • lt/servlet-mappinggt
  • lt/web-appgt
Write a Comment
User Comments (0)
About PowerShow.com