Presentation is loading. Please wait.

Presentation is loading. Please wait.

Hibernate. Hibernate is a powerful, high performance object/relational persistence and query service. Hibernate lets you develop persistent classes following.

Similar presentations


Presentation on theme: "Hibernate. Hibernate is a powerful, high performance object/relational persistence and query service. Hibernate lets you develop persistent classes following."— Presentation transcript:

1 Hibernate

2 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.LGPL

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.Java EE 5.0EJB 3.0 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.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.3.4.0 GAChangelogRoad Map 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. Many Hibernate tutorials out there: http://www.hibernate.org/hib_docs/reference/en/ html/tutorial.htmlhttp://www.hibernate.org/hib_docs/reference/en/ html/tutorial.html http://www.roseindia.net/hibernate/index.shtml http://www.hibernate.org/hib_docs/reference/en/ html/tutorial-webapp.htmlhttp://www.hibernate.org/hib_docs/reference/en/ html/tutorial-webapp.html http://www.inf.ed.ac.uk/teaching/courses/ec/han douts/quickstart.pdfhttp://www.inf.ed.ac.uk/teaching/courses/ec/han douts/quickstart.pdf

6 Hibernate tutorials Various modified/new tutorials appear here. I used mysql, but that is not a requirement. 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 A hibernate app (not a web app!) Will consist of one or more classes (POJOs) to be populated from/copied to database tables. A mapping file for each named classname.hbm.xml mapping each to the database table it corresponds to Configuration files as needed for log4j and hibernate… especially hibernate.cfg.xml A controller class And so on…

8 First hibernate tutorial Using hibernate with a mysql database and a few simple java classes. Link for tutorial: http://www.hibernate.org/hib_docs/referen ce/en/html/tutorial-firstapp.html http://www.hibernate.org/hib_docs/referen ce/en/html/tutorial-firstapp.html This tutorial has many omissions, most notably library jar files needed. I also had to modify some classes (HibernateUtil). It does come with an ant build

9 Directory structure Appdir –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

10 Notes about lib You’ll need Hibernate Cp30 Antlr Jta Dom4j Commons logging Just 2 files from slf4j…note screen shot

11 My lib directory

12 build.xml <javac srcdir="${sourcedir}" destdir="${targetdir}" classpathref="libraries"/>

13 HibernateUtil.java This class gets the hibernate session factory or throws an exception With minor variations it appears in many hibernate applications

14 HibernateUtil.java package util; 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() { return sessionFactory; }

15 EventManager.java (also in slide notes)… a controller class for handling “events” 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 (args[0].equals("store")) {//if  ------A store command System.out.println("create and store"); mgr.createAndStoreEvent("My Event", new Date()); }//if else if (args[0].equals("list")) {//  ------A list command System.out.println("list events"); List events = mgr.listEvents(); for (int i = 0; i < events.size(); i++) { Event theEvent = (Event) events.get(i); System.out.println("Event: " + theEvent.getTitle() + " Time: " + theEvent.getDate()); } }System.out.println("Event Manager: completed if"); HibernateUtil.getSessionFactory().close(); }

16 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); theEvent.setDate(theDate); session.save(theEvent); System.out.println("session save completed"); session.getTransaction().commit(); System.out.println("after commit in create and save"); }

17 Event.java package events; import java.util.Date; public class Event { private Long id; private String title; private Date date; //Eclipse or Netbeans will build the rest… default constructor and getter/setters 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; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; }

18 Event.hbm.xml --such a file (and the corresponding java class) is needed for each table mapped…note how primary key autoincrement primary key appears <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

19 hibernate.cfg.xml contains connection info, db name, user name & pw and other information <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> com.mysql.jdbc.Driver jdbc:mysql://localhost/mydb root 10 org.hibernate.dialect.MySQLDialect true update

20 Log4j.properties log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=System.out log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n log4j.rootLogger=info, stdout log4j.logger.org.hibernate.test=info log4j.logger.org.hibernate.tool.hbm2ddl=debug

21 remark You’ll 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 –Daction=store Or ant run –Daction=list

22 First tutorial…output for store C:\hibernateexample>ant run -Daction=store 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 >> [java] 719 [main] INFO org.hibernate.tool.hbm2ddl.SchemaUpdate - schema upd ate complete [java] back from build session factory [java].. before begin transaction [java].. transaction started [java] Hibernate: insert into EVENTS (EVENT_DATE, title) values (?, ?) [java] session save completed [java] after commit in create and save [java] 907 [main] INFO org.hibernate.impl.SessionFactoryImpl - closing [java] 907 [main] INFO org.hibernate.connection.DriverManagerConnectionProv ider - cleaning up connection pool: jdbc:mysql://localhost/mydb [java] Event Manager: completed if BUILD SUCCESSFUL Total time: 2 seconds C:\hibernateexample>

23 Run –list …entirety in notes C:\hibernateexample>ant run -Daction=list Buildfile: build.xml clean: … copy-resources: … compile: [javac] Compiling 3 source files to C:\hibernateexample\bin run: >>> [java] 531 [main] INFO org.hibernate.impl.SessionFactoryImpl - building ses sion factory [java] 719 [main] INFO org.hibernate.impl.SessionFactoryObjectFactory - Not binding factory to JNDI, no JNDI name configured … [title, event_date, event_id] [java] 734 [main] INFO org.hibernate.tool.hbm2ddl.TableMetadata - foreign k eys: [] [java] 734 [main] INFO org.hibernate.tool.hbm2ddl.TableMetadata - indexes: [event_id] [java] 734 [main] INFO org.hibernate.tool.hbm2ddl.SchemaUpdate - schema upd ate complete [java] back from build session factory [java] Hibernate: select event0_.EVENT_ID as EVENT1_0_, event0_.EVENT_DATE as EVENT2_0_, event0_.title as title0_ from EVENTS event0_ [java] Event: My Event Time: 2009-03-03 00:00:00.0 [java] 1062 [main] INFO org.hibernate.impl.SessionFactoryImpl - closing [java] Event Manager: completed if [java] 1062 [main] INFO org.hibernate.connection.DriverManagerConnectionPro vider - cleaning up connection pool: jdbc:mysql://localhost/mydb BUILD SUCCESSFUL Total time: 2 seconds C:\hibernateexample>

24 Redo with a GUI…needs some improvement

25 notes First, of course, get the tutorial working. Modify the EventManager so it opens a JFrame with two button, list and store. Should have another button to delete * from db/table) Display stored events in a textarea. Enter data for the event in a textfield. The tutorial code uses a timestamp, but maybe something else like a string with MM/DD/YY format would be nicer.

26 So what’s the point of hibernate? A uniform connection (the session thingy) and sql dialect in your object. This doesn’t change as you port your application. The hibernate.cfg.xml (NOT your java code) gets modified if you port or change database servers.

27 The hibernate webapp Recall a webapp consists of a servlet (class) sitting in a fixed directory structure, with a web.xml configuration file. A webapp requires a container (Tomcat, Jetty, JBoss,…) to run it. A server would typically include a (servlet) container.

28 Tomcat Web App Directory Structure Your servlet container Dir named Webapps Dir named ROOT A webapp dir Servlets- put html in here WEB-INF web.xml Classes dir- put the packages/.class files here Other web app directories…

29 WEB-INF\web.xml <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> Event Manager events.EventManagerServlet Event Manager /eventmanager

30 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) …if not, then into classes dir

31 The 1-table hibernate web app http://www.hibernate.org/hib_docs/reference/e n/html/tutorial-webapp.htmlhttp://www.hibernate.org/hib_docs/reference/e n/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.

32 Servlet running in tomcat

33 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;

34 Servlet continued protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); SimpleDateFormat dateFormatter = new SimpleDateFormat("dd.MM.yyyy"); PrintWriter out = response.getWriter(); out.println(" Event Manager "); try { sessionFactory = HibernateUtil.getSessionFactory(); session =sessionFactory.openSession(); session.beginTransaction(); if ("store".equals(request.getParameter("action"))) { String eventTitle = request.getParameter("eventTitle"); String eventDate = request.getParameter("eventDate"); if ("".equals(eventTitle) || "".equals(eventDate)) { out.println(" Please enter event title and date. "); } else { System.out.println("before call to create and store"); createAndStoreEvent(eventTitle, dateFormatter.parse(eventDate)); out.println(" Added event. "); } } printEventForm(out); listEvents(out, dateFormatter); // End unit of work //HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().commit(); session.getTransaction().commit(); System.out.println("commit after save"); } catch (Exception ex) { HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().rollback(); throw new ServletException(ex); } }

35 Servlet continued private void printEventForm(PrintWriter out) { out.println(" Add new event: "); out.println(" "); out.println("Title: "); out.println("Date (e.g. 24.12.2009): "); out.println(" "); } private void listEvents(PrintWriter out, SimpleDateFormat dateFormatter) { List result = HibernateUtil.getSessionFactory().getCurrentSession().createCriteria(Event.class).list(); if (result.size() > 0) { out.println(" Events in database: "); out.println(" "); out.println(" Event title "); out.println(" Event date "); out.println(" "); for (Iterator it = result.iterator(); it.hasNext();) { Event event = (Event) it.next(); out.println(" "); out.println(" " + event.getTitle() + " "); out.println(" " + dateFormatter.format(event.getDate()) + " "); out.println(" "); } out.println(" "); }

36 Servlet continued protected void createAndStoreEvent(String title, Date theDate) { Event theEvent = new Event(); theEvent.setTitle(title); theEvent.setDate(theDate); HibernateUtil.getSessionFactory().getCurrentSession().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); }

37 Boldfaced line added to cfg <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> com.mysql.jdbc.Driver jdbc:mysql://localhost/mydb root 10 org.hibernate.dialect.MySQLDialect true update thread

38 build.xml (an app located at c:\myapp would have a war called C:\myapp.war) <javac srcdir="${sourcedir}" destdir="${targetdir}" classpathref="libraries"/>

39 Build.xml continued

40 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 –lib(dir) (no changes to this) –log4j.properties(no changes to this) –web.xml (shown above)

41 Jar I used jar instead of ant build: jar –cvf appname.war WEB-INF This creates a jar called appname.war with a dir in it named WEB-INF and all WEB-INF’s contents. General syntax of jar is jar –switch name-of.war list_of_files list_of_dirs You’ll need to move files and directories as per web app structure before creating a war file.

42 What’s next? CRUD against a database using one or more servlets, like your servlet database project, except use a hibernate interface.

43 Two examples: multiple tables & crud documentation http://www.hibernate.org/hib_docs/referen ce/en/html/ http://www.hibernate.org/hib_docs/referen ce/en/html/

44

45 Adding to tables & listing I modified a 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 id=number

46 My tables My People table and my Event table both have ids as primary key, auto-incremented. In the hbm, these are identified as

47 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)

48 some of these may be unnecessary but I whittled it down some

49 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(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); SimpleDateFormat dateFormatter = new SimpleDateFormat("dd.MM.yyyy"); PrintWriter out = response.getWriter(); out.println(" Event Manager "); try { // Begin unit of work // HibernateUtil.getSessionFactory().getCurrentSession().beginTransaction(); sessionFactory = HibernateUtil.getSessionFactory(); session =sessionFactory.openSession(); session.beginTransaction();

50 Servlet…print 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.equals("")) { out.println(" Please enter person, event title and date. "); } else { System.out.println("before call to create and store"); createAndStoreEvent(name, phone,eventTitle, dateFormatter.parse(eventDate)); out.println(" Added event. "); } // Print page printEventForm(out); System.out.println("back in process...about to call listevents"); listEvents(out, dateFormatter); // End unit of work //HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().commit(); session.getTransaction().commit(); System.out.println("commit after save"); } catch (Exception ex) { System.out.println(ex.toString()); HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().rollback(); throw new ServletException(ex); }

51 Servlet: the form and table of events private void printEventForm(PrintWriter out) { out.println(" Add new event: "); out.println(" "); out.println("Title: "); out.println("Date (e.g. 24.12.2009): "); out.println("Contact person: "); out.println("Phone(e.g. (123) 432-1111: "); out.println(" "); } private void listEvents(PrintWriter out, SimpleDateFormat dateFormatter) { result1 = session.createCriteria(Event.class).list(); if (result1.size() > 0) { out.println(" Event Info in database: "); out.println(" "); out.println(" Event title "); out.println(" Event date "); out.println(" Event id "); out.println(" "); for (Iterator it = result1.iterator(); it.hasNext();) { Event event = (Event) it.next(); out.println(" "); out.println(" " + event.getTitle()+ " "); out.println(" " + dateFormatter.format(event.getDate()) + " "); out.println(" " + event.getId() + " "); out.println(" "); } out.println(" "); }//if

52 Servlet… list table of people int num=0; result2 = session.createCriteria(People.class).list(); if (result2.size() > 0) { out.println(" People Info in database: "); out.println(" "); out.println(" Person "); out.println(" Phone "); out.println(" Event coordinating "); out.println(" "); String unknown="unknown"; for (Iterator it = result2.iterator(); it.hasNext();) { People person=(People)it.next(); out.println(" "); out.println(" " + person.getName() + " "); out.println(" " + person.getPhone() + " "); out.println(" " + ((Event)result1.get(num)).getTitle() + " "); num++; out.println(" "); } out.println(" "); }

53 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 person=new 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"); processRequest(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("in do post"); doGet(request, response); }

54 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.id=id;} public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; }

55 The primary key may be generated, native or assigned. The strategy must be specified in the hbm.xml. This is People.hbm.xml <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

56 Same hibernate.cfg.xml except People table has been added. <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> com.mysql.jdbc.Driver jdbc:mysql://localhost/mydb root 10 org.hibernate.dialect.MySQLDialect org.hibernate.cache.NoCacheProvider true update thread

57 ant build – still needs to be modified to build WEB-INF and classes dirs, and copy files to there, then jar <javac srcdir="${sourcedir}" destdir="${targetdir}" classpathref="libraries"/>

58 CRUD example The student table

59 Hibernate student info servlet

60 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

61 Student.hbm.xml <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

62 Some bits of the servlet try { // Begin unit of work // HibernateUtil.getSessionFactory().getCurrentSession().beginTransaction(); sessionFactory = HibernateUtil.getSessionFactory(); 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("")||age.equals("")) { out.println(" Please enter name, age, sex, gpa, year and sex. "); } else { System.out.println("before call to create and store"); createAndStoreEvent(name, age,year,sex,gpa); out.println(" Added event. "); } } else if ("list".equals(request.getParameter("action"))) { // Print page System.out.println("back in process...about to call listevents"); listStudents(out); }

63 Delete action else if ("delete".equals(request.getParameter("action"))) { String name = request.getParameter("name"); List marked=session.createQuery("from Student as student where student.name=?").setString(0,name).list(); if(marked.size()>0){ Student student=(Student)marked.get(0); out.println("deleting...."+ student.getName()); session.delete(student); } else {out.println("no match found");}

64 }else{//update 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"); List marked=session.createQuery("from Student as student where student.name=?").setString(0,name).list(); if(marked.size()>0&&!"".equals(sex)&&!year.equals("")&&!gpa.equals("")&&!age.equal s("")) { 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 */

65 I used radiobuttons private void printStudentForm(PrintWriter out) { out.println(" Student info form: "); out.println(" "); out.println("Name: "); out.println("Age: "); out.println("Sex(Male/Female): "); out.println("Year: "); out.println("GPA: "); out.println(" List "); out.println(" Store "); out.println(" Update "); out.println(" Delete "); out.println(" "); }

66 List students private void listStudents(PrintWriter out) { result1 = session.createCriteria(Student.class).list(); if (result1.size() > 0) { out.println(" Student Info: "); out.println(" "); out.println(" Student name "); out.println(" Student Age "); out.println(" GPA "); out.println(" Sex "); out.println(" Year "); out.println(" "); for (Iterator it = result1.iterator(); it.hasNext();) { Student student = (Student) it.next(); out.println(" "); out.println(" " + student.getName()+ " "); out.println(" " + student.getAge() + " "); out.println(" " + student.getGpa() + " "); out.println(" " + student.getSex() + " "); out.println(" " + student.getYear() + " "); out.println(" "); } out.println(" "); }//if }

67 Hibernate configuration <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> com.mysql.jdbc.Driver jdbc:mysql://localhost/mydb root 10 org.hibernate.dialect.MySQLDialect true update

68 web-xml <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> StudentInfo data.StudentInfoServlet StudentInfo /studentinfo


Download ppt "Hibernate. Hibernate is a powerful, high performance object/relational persistence and query service. Hibernate lets you develop persistent classes following."

Similar presentations


Ads by Google