Hibernate Hibernate Hibernate is a powerful high performance
Hibernate
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.
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 Entity. Manager 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.
Hibernate Annotations • Project Lead: Emmanuel Bernard. Latest release: 3. 4. 0 GA (Changelog) (Road Map)Release date: 20. 08. 2008 Requirements: Hibernate Core 3. 3. x, JDK 5. 0 Hibernate, 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.
More jar file downloads • You will need persistence and ejb jar files: ejb, persistence, jndi, geronimo-ejb, ejb 3 -persistence and javaee. • Many Hibernate tutorials out there: • http: //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. html • http: //www. inf. ed. ac. uk/teaching/courses/ec/han douts/quickstart. pdf
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.
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 log 4 j and hibernate… especially hibernate. cfg. xml • A controller class • And so on…
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 • This tutorial has many omissions, most notably library jar files needed. I also had to modify some classes (Hibernate. Util). • It does come with an ant build
Directory structure • Appdir – bin – src • • • log 4 j. properties hibernate. cfg. xml Event. hbm. xml hibernate. properties --- not included in this example events(dir) – Event. java • util(dir) – Event. Manager. java – Hibernate. Util. java – lib
Notes about lib • • You’ll need Hibernate Cp 30 Antlr Jta Dom 4 j Commons logging Just 2 files from slf 4 j…note screen shot
My lib directory
build. xml <project name="hibernate-tutorial" default="compile"> <property name="sourcedir" value="${basedir}/src"/> <property name="targetdir" value="${basedir}/bin"/> <property name="librarydir" value="${basedir}/lib"/> <path id="libraries"> <fileset dir="${librarydir}"> <include name="*. jar"/> </fileset> </path> <target name="clean"> <delete dir="${targetdir}"/> <mkdir dir="${targetdir}"/> </target> <target name="compile" depends="clean, copy-resources"> <javac srcdir="${sourcedir}" destdir="${targetdir}" classpathref="libraries"/> </target> <target name="copy-resources"> <copy todir="${targetdir}"> <fileset dir="${sourcedir}"> <exclude name="**/*. java"/> </fileset> </copy> </target> <target name="run" depends="compile"> <java fork="true" classname="events. Event. Manager" classpathref="libraries"> <classpath="${targetdir}"/> <arg value="${action}"/> </java> </target> </project>
Hibernate. Util. java • This class gets the hibernate session factory or throws an exception • With minor variations it appears in many hibernate applications
Hibernate. Util. java package util; import org. hibernate. *; import org. hibernate. cfg. *; public class Hibernate. Util { private static final Session. Factory session. Factory; static { try { System. out. println("in try for build session factory"); // Create the Session. Factory from hibernate. cfg. xml session. Factory = new Configuration(). configure(). build. Session. Factory(); 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 Session. Factory creation failed. " + ex); System. out. println("Initial Session. Factory creation failed. " + ex); throw new Exception. Initializer. Error(ex); } } public static Session. Factory get. Session. Factory() { return session. Factory; } }
Event. Manager. 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. Hibernate. Util; public class Event. Manager { public static void main(String[] args) {//main Event. Manager mgr = new Event. Manager(); 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. create. And. Store. Event("My Event", new Date()); }//if else if (args[0]. equals("list")) {// ------A list command System. out. println("list events"); List events = mgr. list. Events(); for (int i = 0; i < events. size(); i++) { Event the. Event = (Event) events. get(i); System. out. println("Event: " + the. Event. get. Title() + " Time: " + the. Event. get. Date()); } }System. out. println("Event Manager: completed if"); Hibernate. Util. get. Session. Factory(). close(); }
Event. Manager. java continued private List list. Events() { System. out. println("Event Manager. . . in list events method"); Session. Factory session. Factory = Hibernate. Util. get. Session. Factory(); Session session =session. Factory. open. Session(); session. begin. Transaction(); List result = session. create. Query("from Event"). list(); session. get. Transaction(). commit(); return result; } private void create. And. Store. Event(String title, Date the. Date) { System. out. println("Event Manager. . . create and store method"); Session. Factory session. Factory = Hibernate. Util. get. Session. Factory(); Session session =session. Factory. open. Session(); System. out. println(". . before begin transaction"); session. begin. Transaction(); System. out. println(". . transaction started"); Event the. Event = new Event(); the. Event. set. Title(title); the. Event. set. Date(the. Date); session. save(the. Event); System. out. println("session save completed"); session. get. Transaction(). commit(); System. out. println("after commit in create and save"); } }
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 get. Id() { return id; } private void set. Id(Long id) { this. id = id; } public Date get. Date() { return date; } public void set. Date(Date date) { this. date = date; } public String get. Title() { return title; } public void set. Title(String title) { this. title = title; } }
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 <? xml version="1. 0"? > <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate Mapping DTD 3. 0//EN" "http: //hibernate. sourceforge. net/hibernate-mapping-3. 0. dtd"> <hibernate-mapping> <class name="events. Event" table="EVENTS"> <id name="id" column="EVENT_ID"> <generator class="native"/> </id> <property name="date" type="timestamp" column="EVENT_DATE"/> <property name="title"/> </class> </hibernate-mapping>
hibernate. cfg. xml contains connection info, db name, user name & pw and other information <? xml version='1. 0' encoding='utf-8'? > <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate Configuration DTD 3. 0//EN" "http: //hibernate. sourceforge. net/hibernate-configuration-3. 0. dtd"> <hibernate-configuration> <session-factory> <!-- Database connection settings --> <property name="connection. driver_class">com. mysql. jdbc. Driver</property> <property name="connection. url">jdbc: mysql: //localhost/mydb</property> <property name="connection. username">root</property> <property name="connection. password"></property> <!-- JDBC connection pool (use the built-in) --> <property name="hibernate. connection. pool_size">10</property> <!-- My. SQL dialect//different for different Database --> <property name="dialect">org. hibernate. dialect. My. SQLDialect</property> <!-- Echo all executed SQL to stdout --> <property name="show_sql">true</property> <property name="hbm 2 ddl. auto">update</property> <mapping resource="Event. hbm. xml"/> </session-factory> </hibernate-configuration>
Log 4 j. properties log 4 j. appender. stdout=org. apache. log 4 j. Console. Appender log 4 j. appender. stdout. Target=System. out log 4 j. appender. stdout. layout=org. apache. log 4 j. Pattern. Layout log 4 j. appender. stdout. layout. Conversion. Pattern=%d{ABSOLUTE} %5 p %c{1}: %L - %m%n log 4 j. root. Logger=info, stdout log 4 j. logger. org. hibernate. test=info log 4 j. logger. org. hibernate. tool. hbm 2 ddl=debug
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
First tutorial…output for store C: hibernateexample>ant run -Daction=store Buildfile: build. xml clean: [delete] Deleting directory C: hibernateexamplebin [mkdir] Created dir: C: hibernateexamplebin copy-resources: [copy] Copying 6 files to C: hibernateexamplebin [copy] Copied 2 empty directories to 1 empty directory under C: hibernateex amplebin compile: [javac] Compiling 3 source files to C: hibernateexamplebin run: [java] Event Manager before if [java] create and store [java] Event Manager. . . create and store method [java] in try for build session factory <<<omitted a lot…see slide notes>>> [java] 719 [main] INFO org. hibernate. tool. hbm 2 ddl. Schema. Update - 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. Session. Factory. Impl - closing [java] 907 [main] INFO org. hibernate. connection. Driver. Manager. Connection. Prov ider - cleaning up connection pool: jdbc: mysql: //localhost/mydb [java] Event Manager: completed if BUILD SUCCESSFUL Total time: 2 seconds C: hibernateexample>
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: hibernateexamplebin run: <<left out a lot of output here>>>> [java] 531 [main] INFO org. hibernate. impl. Session. Factory. Impl - building ses sion factory [java] 719 [main] INFO org. hibernate. impl. Session. Factory. Object. Factory - Not binding factory to JNDI, no JNDI name configured … [title, event_date, event_id] [java] 734 [main] INFO org. hibernate. tool. hbm 2 ddl. Table. Metadata - foreign k eys: [] [java] 734 [main] INFO org. hibernate. tool. hbm 2 ddl. Table. Metadata - indexes: [event_id] [java] 734 [main] INFO org. hibernate. tool. hbm 2 ddl. Schema. Update - schema upd ate complete [java] back from build session factory [java] Hibernate: select event 0_. EVENT_ID as EVENT 1_0_, event 0_. EVENT_DATE as EVENT 2_0_, event 0_. title as title 0_ from EVENTS event 0_ [java] Event: My Event Time: 2009 -03 -03 00: 00. 0 [java] 1062 [main] INFO org. hibernate. impl. Session. Factory. Impl - closing [java] Event Manager: completed if [java] 1062 [main] INFO org. hibernate. connection. Driver. Manager. Connection. Pro vider - cleaning up connection pool: jdbc: mysql: //localhost/mydb BUILD SUCCESSFUL Total time: 2 seconds C: hibernateexample>
Redo with a GUI…needs some improvement
notes • First, of course, get the tutorial working. • Modify the Event. Manager 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.
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.
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.
Tomcat Web App Directory Structure Your servlet container Dir named Webapps Dir named ROOT Other web app directories… A webapp dir Servlets- put html in here WEB-INF web. xml lib Classes dir- put the packages/. class files here
WEB-INFweb. xml <? xml version="1. 0" encoding="UTF-8"? > <web-app version="2. 4" xmlns="http: //java. sun. com/xml/ns/j 2 ee" xmlns: xsi="http: //www. w 3. org/2001/XMLSchema-instance" xsi: schema. Location="http: //java. sun. com/xml/ns/j 2 ee/web-app_2_4. xsd"> <servlet> <servlet-name>Event Manager</servlet-name> <servlet-class>events. Event. Manager. Servlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Event Manager</servlet-name> <url-pattern>/eventmanager</url-pattern> </servlet-mapping> </web-app>
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
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 Hibernate. Util class (shown in previous tutorial). • Not very many details about the directory structure were given in the tutorial, but I give them here.
Servlet running in tomcat
Servlet entirety in slide notes package events; import java. io. *; import java. net. *; import java. text. Simple. Date. Format; import java. util. Date; import java. util. Iterator; import java. util. List; import javax. servlet. *; import javax. servlet. http. *; import util. Hibernate. Util; import org. hibernate. *; public class Event. Manager. Servlet extends Http. Servlet { Session. Factory session. Factory; Session session;
Servlet continued protected void process. Request(Http. Servlet. Request request, Http. Servlet. Response response) throws Servlet. Exception, IOException { response. set. Content. Type("text/html; charset=UTF-8"); Simple. Date. Format date. Formatter = new Simple. Date. Format("dd. MM. yyyy"); Print. Writer out = response. get. Writer(); out. println("<html><head><title>Event Manager</title></head><body>"); try { session. Factory = Hibernate. Util. get. Session. Factory(); session =session. Factory. open. Session(); session. begin. Transaction(); if ("store". equals(request. get. Parameter("action"))) { String event. Title = request. get. Parameter("event. Title"); String event. Date = request. get. Parameter("event. Date"); if ("". equals(event. Title) || "". equals(event. Date)) { out. println("<b><i>Please enter event title and date. </i></b>"); } else { System. out. println("before call to create and store"); create. And. Store. Event(event. Title, date. Formatter. parse(event. Date)); out. println("<b><i>Added event. </i></b>"); } } print. Event. Form(out); list. Events(out, date. Formatter); // End unit of work //Hibernate. Util. get. Session. Factory(). get. Current. Session(). get. Transaction(). commit(); session. get. Transaction(). commit(); System. out. println("commit after save"); } catch (Exception ex) { Hibernate. Util. get. Session. Factory(). get. Current. Session(). get. Transaction(). rollback(); throw new Servlet. Exception(ex); } }
Servlet continued private void print. Event. Form(Print. Writer out) { out. println("<h 2>Add new event: </h 2>"); out. println("<form>"); out. println("Title: <input name='event. Title' length='50'/><br/>"); out. println("Date (e. g. 24. 12. 2009): <input name='event. Date' length='10'/><br/>"); out. println("<input type='submit' name='action' value='store'/>"); out. println("</form>"); } private void list. Events(Print. Writer out, Simple. Date. Format date. Formatter) { List result = Hibernate. Util. get. Session. Factory(). get. Current. Session(). create. Criteria(Event. class). list(); if (result. size() > 0) { out. println("<h 2>Events in database: </h 2>"); out. println("<table border='1'>"); out. println("<tr>"); out. println("<th>Event title</th>"); out. println("<th>Event date</th>"); out. println("</tr>"); for (Iterator it = result. iterator(); it. has. Next(); ) { Event event = (Event) it. next(); out. println("<tr>"); out. println("<td>" + event. get. Title() + "</td>"); out. println("<td>" + date. Formatter. format(event. get. Date()) + "</td>"); out. println("</tr>"); } out. println("</table>"); } }
Servlet continued protected void create. And. Store. Event(String title, Date the. Date) { Event the. Event = new Event(); the. Event. set. Title(title); the. Event. set. Date(the. Date); Hibernate. Util. get. Session. Factory(). get. Current. Session(). save(the. Event); } protected void do. Get(Http. Servlet. Request request, Http. Servlet. Response response) throws Servlet. Exception, IOException { process. Request(request, response); } protected void do. Post(Http. Servlet. Request request, Http. Servlet. Response response) throws Servlet. Exception, IOException { process. Request(request, response); } }
Boldfaced line added to cfg <? xml version='1. 0' encoding='utf-8'? > <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate Configuration DTD 3. 0//EN" "http: //hibernate. sourceforge. net/hibernate-configuration-3. 0. dtd"> <hibernate-configuration> <session-factory> <!-- Database connection settings --> <property name="connection. driver_class">com. mysql. jdbc. Driver</property> <property name="connection. url">jdbc: mysql: //localhost/mydb</property> <property name="connection. username">root</property> <property name="connection. password"></property> <!-- JDBC connection pool (use the built-in) --> <property name="hibernate. connection. pool_size">10</property> <!-- My. SQL dialect//different for different Database --> <property name="dialect">org. hibernate. dialect. My. SQLDialect</property> <!-- Echo all executed SQL to stdout --> <property name="show_sql">true</property> <property name="hbm 2 ddl. auto">update</property> <property name="current_session_context_class">thread</property> <mapping resource="Event. hbm. xml"/> </session-factory> </hibernate-configuration>
build. xml (an app located at c: myapp would have a war called C: myapp. war) <project name="hibernate-tutorial" default="compile"> <property name="sourcedir" value="${basedir}/src"/> <property name="targetdir" value="${basedir}/bin"/> <property name="librarydir" value="${basedir}/lib"/> <path id="libraries"> <fileset dir="${librarydir}"> <include name="*. jar"/> </fileset> </path> <target name="clean"> <delete dir="${targetdir}"/> <mkdir dir="${targetdir}"/> </target> <target name="compile" depends="clean, copy-resources"> <javac srcdir="${sourcedir}" destdir="${targetdir}" classpathref="libraries"/> </target> <target name="copy-resources"> <copy todir="${targetdir}"> <fileset dir="${sourcedir}"> <exclude name="**/*. java"/> </fileset> </copy> </target>
Build. xml continued <target name="run" depends="compile"> <java fork="true" classname="events. Event. Manager 2" classpathref="libraries"> <classpath="${targetdir}"/> <arg value="${action}"/> </java> </target> <target name="war" depends="compile"> <war destfile="hibernate-tutorial. war" webxml="web. xml"> <lib dir="${librarydir}"> <exclude name="jsdk*. jar"/> </lib> <classes dir="${targetdir}"/> </war> </target> </project>
Package things in WEB-INF as shown here • WEB-INF – classes (dir) • events(dir) – Event. class (no changes to this file) – Event. Manager. Servlet. class – Event. hbm. xml (no changes to this file) • util(dir) – Hibernate. Util. class (this file same as in previous project) • Hibernate. cfg. xml – lib(dir) (no changes to this) – log 4 j. properties(no changes to this) – web. xml (shown above)
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.
What’s next? • CRUD against a database using one or more servlets, like your servlet database project, except use a hibernate interface.
Two examples: multiple tables & crud • documentation http: //www. hibernate. org/hib_docs/referen ce/en/html/
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
My tables • My People table and my Event table both have ids as primary key, auto-incremented. • In the hbm, these are identified as <id name=“some_field" column=“table_col"> <generator class="native"/> </id>
Dir structure • WEB-INF – – log 4 j. properties web. xml lib (contents shown later) classes • hibernate. cfg. xml • util – Same Hibernate. Util. java as previous • events – – – Same Event. java as previous People. java Event. Manager. Servlet. java People. hbm. xml Event. hbm. xml (unchanged from prev example)
some of these may be unnecessary but I whittled it down some
Entire Servlet in notes package events; import java. io. *; import java. net. *; import java. text. Simple. Date. Format; import java. util. Date; import java. util. Iterator; import java. util. List; import javax. servlet. *; import javax. servlet. http. *; import util. Hibernate. Util; import org. hibernate. *; public class Event. Manager. Servlet extends Http. Servlet { Session. Factory session. Factory; List result 1, result 2; Session session; protected void process. Request(Http. Servlet. Request request, Http. Servlet. Response response) throws Servlet. Exception, IOException { response. set. Content. Type("text/html; charset=UTF-8"); Simple. Date. Format date. Formatter = new Simple. Date. Format("dd. MM. yyyy"); Print. Writer out = response. get. Writer(); out. println("<html><head><title>Event Manager</title></head><body>"); try { // Begin unit of work // Hibernate. Util. get. Session. Factory(). get. Current. Session(). begin. Transaction(); session. Factory = Hibernate. Util. get. Session. Factory(); session =session. Factory. open. Session(); session. begin. Transaction();
Servlet…print form, get session // Handle actions if ("store". equals(request. get. Parameter("action"))) { String event. Title = request. get. Parameter("event. Title"); String event. Date = request. get. Parameter("event. Date"); String name = request. get. Parameter("name"); String phone = request. get. Parameter("phone"); if ("". equals(event. Title) || "". equals(event. Date)||name. equals("")||phone. equals("")) { out. println("<b><i>Please enter person, event title and date. </i></b>"); } else { System. out. println("before call to create and store"); create. And. Store. Event(name, phone, event. Title, date. Formatter. parse(event. Date)); out. println("<b><i>Added event. </i></b>"); } // Print page print. Event. Form(out); System. out. println("back in process. . . about to call listevents"); list. Events(out, date. Formatter); // End unit of work //Hibernate. Util. get. Session. Factory(). get. Current. Session(). get. Transaction(). commit(); session. get. Transaction(). commit(); System. out. println("commit after save"); } catch (Exception ex) { System. out. println(ex. to. String()); Hibernate. Util. get. Session. Factory(). get. Current. Session(). get. Transaction(). rollback(); throw new Servlet. Exception(ex); } }
Servlet: the form and table of events private void print. Event. Form(Print. Writer out) { out. println("<h 2>Add new event: </h 2>"); out. println("<form>"); out. println("Title: <input name='event. Title' length='50'/><br/>"); out. println("Date (e. g. 24. 12. 2009): <input name='event. Date' length='10'/><br/>"); out. println("Contact person: <input name='name' length='50'/><br/>"); out. println("Phone(e. g. (123) 432 -1111: <input name='phone' length='50'/><br/>"); out. println("<input type='submit' name='action' value='store'/>"); out. println("</form>"); } private void list. Events(Print. Writer out, Simple. Date. Format date. Formatter) { result 1 = session. create. Criteria(Event. class). list(); if (result 1. size() > 0) { out. println("<h 2>Event Info in database: </h 2>"); out. println("<table border='1'>"); out. println("<tr>"); out. println("<th>Event title</th>"); out. println("<th>Event date</th>"); out. println("<th>Event id</th>"); out. println("</tr>"); for (Iterator it = result 1. iterator(); it. has. Next(); ) { Event event = (Event) it. next(); out. println("<tr>"); out. println("<td>" + event. get. Title()+ "</td>"); out. println("<td>" + date. Formatter. format(event. get. Date()) + "</td>"); out. println("<td>" + event. get. Id() + "</td>"); out. println("</tr>"); } out. println("</table>"); }//if
Servlet… list table of people int num=0; result 2 = session. create. Criteria(People. class). list(); if (result 2. size() > 0) { out. println("<h 2>People Info in database: </h 2>"); out. println("<table border='1'>"); out. println("<tr>"); out. println("<th>Person</th>"); out. println("<th>Phone</th>"); out. println("<th>Event coordinating</th>"); out. println("</tr>"); String unknown="unknown"; for (Iterator it = result 2. iterator(); it. has. Next(); ) { People person=(People)it. next(); out. println("<tr>"); out. println("<td>" + person. get. Name() + "</td>"); out. println("<td>" + person. get. Phone() + "</td>"); out. println("<td>" + ((Event)result 1. get(num)). get. Title() + "</td>"); num++; out. println("</tr>"); } out. println("</table>"); } }
Create and store protected void create. And. Store. Event(String name, String phone, String title, Date the. Date) { System. out. println("in create and store method"); Event the. Event = new Event(); People person=new People(); the. Event. set. Title(title); the. Event. set. Date(the. Date); person. set. Name(name); person. set. Phone(phone); System. out. println("about to get current session and save event"); session. save(the. Event); System. out. println("about to get current session and save person"); session. save(person); System. out. println("done with saves"); } protected void do. Get(Http. Servlet. Request request, Http. Servlet. Response response) throws Servlet. Exception, IOException { System. out. println("in do get"); process. Request(request, response); } protected void do. Post(Http. Servlet. Request request, Http. Servlet. Response response) throws Servlet. Exception, IOException { System. out. println("in do post"); do. Get(request, response); } }
events. People. java public class People{ private String name; private String phone; private long id; public People() {} public long get. Id(){return id; } public void set. Id(long id){this. id=id; } public String get. Name() { return name; } public void set. Name(String name) { this. name = name; } public String get. Phone() { return phone; } public void set. Phone(String phone) { this. phone = phone; } }
The primary key may be generated, native or assigned. The strategy must be specified in the hbm. xml. This is People. hbm. xml <? xml version="1. 0"? > <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate Mapping DTD 3. 0//EN" "http: //hibernate. sourceforge. net/hibernate-mapping-3. 0. dtd"> <hibernate-mapping> <class name="events. People" table="people"> <id name="id" column="id"> <generator class="native"/> </id> <property name="name"/> <property name="phone"/> </class> </hibernate-mapping>
Same hibernate. cfg. xml except People table has been added. <? xml version='1. 0' encoding='utf-8'? > <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate Configuration DTD 3. 0//EN" "http: //hibernate. sourceforge. net/hibernate-configuration-3. 0. dtd"> <hibernate-configuration> <session-factory> <!-- Database connection settings --> <property name="connection. driver_class">com. mysql. jdbc. Driver</property> <property name="connection. url">jdbc: mysql: //localhost/mydb</property> <property name="connection. username">root</property> <property name="connection. password"></property> <!-- JDBC connection pool (use the built-in) --> <property name="hibernate. connection. pool_size">10</property> <!-- My. SQL dialect//different for different Database --> <property name="dialect">org. hibernate. dialect. My. SQLDialect</property> <property name="cache. provider_class">org. hibernate. cache. No. Cache. Provider</property> <!-- Echo all executed SQL to stdout --> <property name="show_sql">true</property> <property name="hbm 2 ddl. auto">update</property> <property name="current_session_context_class">thread</property> <mapping resource="events/Event. hbm. xml"/> <mapping resource="events/People. hbm. xml"/> </session-factory> </hibernate-configuration>
ant build – still needs to be modified to build WEB-INF and classes dirs, and copy files to there, then jar <project name="hibernate-tutorial" default="compile"> <property name="sourcedir" value="${basedir}/src"/> <property name="targetdir" value="${basedir}/bin"/> <property name="librarydir" value="${basedir}/lib"/> <path id="libraries"> <fileset dir="${librarydir}"> <include name="*. jar"/> </fileset> </path> <target name="clean"> <delete dir="${targetdir}"/> <mkdir dir="${targetdir}"/> </target> <target name="compile" depends="clean, copy-resources"> <javac srcdir="${sourcedir}" destdir="${targetdir}" classpathref="libraries"/> </target> <target name="copy-resources"> <copy todir="${targetdir}"> <fileset dir="${sourcedir}"> <exclude name="**/*. java"/> </fileset> </copy> </target> <target name="war" depends="compile"> <war destfile="Hibernate. App 2. war" webxml="web. xml"> <lib dir="${librarydir}"> </lib> <classes dir="${targetdir}"/> </war> </target> </project>
CRUD example • The student table
Hibernate student info servlet
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
Student. hbm. xml <? xml version="1. 0"? > <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate Mapping DTD 3. 0//EN" "http: //hibernate. sourceforge. net/hibernate-mapping-3. 0. dtd"> <hibernate-mapping> <class name="data. Student" table="Students"> <id name="id" column="id"> <generator class="native"/> </id> <property name="name"/> <property name="age"/> <property name="gpa"/> <property name="sex"/> <property name="year"/> </class> </hibernate-mapping>
Some bits of the servlet try { // Begin unit of work // Hibernate. Util. get. Session. Factory(). get. Current. Session(). begin. Transaction(); session. Factory = Hibernate. Util. get. Session. Factory(); session =session. Factory. open. Session(); session. begin. Transaction(); if ("store". equals(request. get. Parameter("action"))) { String name = request. get. Parameter("name"); String gpa = request. get. Parameter("gpa"); String year = request. get. Parameter("year"); String age = request. get. Parameter("age"); String sex = request. get. Parameter("sex"); if ("". equals(name) || "". equals(sex)||year. equals("")||gpa. equals("")||age. equals("")) { out. println("<b><i>Please enter name, age, sex, gpa, year and sex. </i></b>"); } else { System. out. println("before call to create and store"); create. And. Store. Event(name, age, year, sex, gpa); out. println("<b><i>Added event. </i></b>"); } } else if ("list". equals(request. get. Parameter("action"))) { // Print page System. out. println("back in process. . . about to call listevents"); list. Students(out); }
Delete action else if ("delete". equals(request. get. Parameter("action"))) { String name = request. get. Parameter("name"); List marked=session. create. Query("from Student as student where student. name=? "). set. String(0, name). list(); if(marked. size()>0){ Student student=(Student)marked. get(0); out. println("deleting. . "+ student. get. Name()); session. delete(student); } else {out. println("no match found"); }
}else{//update String name = request. get. Parameter("name"); String gpa = request. get. Parameter("gpa"); String year = request. get. Parameter("year"); String age = request. get. Parameter("age"); String sex = request. get. Parameter("sex"); List marked=session. create. Query("from Student as student where student. name=? "). set. String(0, name). list(); if(marked. size()>0&&!"". equals(sex)&&!year. equals("")&&!gpa. equals("")&&!age. equal s("")) { Student student=(Student)marked. get(0); student. set. Age(Integer. parse. Int(age)); student. set. Year(year); student. set. Gpa(Double. parse. Double(gpa)); student. set. Sex(sex); session. update(student); } else {out. println("no match found"); } } /*else a getinfo choice could look about the same */
I used radiobuttons private void print. Student. Form(Print. Writer out) { out. println("<h 2>Student info form: </h 2>"); out. println("<form>"); out. println("Name: <input name='name' length='40'/><br/>"); out. println("Age: <input name='age' length='10'/><br/>"); out. println("Sex(Male/Female): <input name='sex' length='10'/><br/>"); out. println("Year: <input name='year' length='15'/><br/>"); out. println("GPA: <input name='gpa' length='10'/><br/>"); out. println("<input type='radio' name='action' value='list'> List "); out. println(" <input type='radio' name='action' value='store' checked> Store "); out. println("<input type='radio' name='action' value='update'> Update "); out. println(" <input type='radio' name='action' value='delete'> Delete "); out. println("<input type='submit' />"); out. println("</form>"); }
List students private void list. Students(Print. Writer out) { result 1 = session. create. Criteria(Student. class). list(); if (result 1. size() > 0) { out. println("<h 2>Student Info: </h 2>"); out. println("<table border='1'>"); out. println("<tr>"); out. println("<th>Student name</th>"); out. println("<th>Student Age</th>"); out. println("<th>GPA</th>"); out. println("<th>Sex</th>"); out. println("<th>Year</th>"); out. println("</tr>"); for (Iterator it = result 1. iterator(); it. has. Next(); ) { Student student = (Student) it. next(); out. println("<tr>"); out. println("<td>" + student. get. Name()+ "</td>"); out. println("<td>" + student. get. Age() + "</td>"); out. println("<td>" + student. get. Gpa() + "</td>"); out. println("<td>" + student. get. Sex() + "</td>"); out. println("<td>" + student. get. Year() + "</td>"); out. println("</tr>"); } out. println("</table>"); }//if }
Hibernate configuration <? xml version='1. 0' encoding='utf-8'? > <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate Configuration DTD 3. 0//EN" "http: //hibernate. sourceforge. net/hibernate-configuration-3. 0. dtd"> <hibernate-configuration> <session-factory> <!-- Database connection settings --> <property name="connection. driver_class">com. mysql. jdbc. Driver</property> <property name="connection. url">jdbc: mysql: //localhost/mydb</property> <property name="connection. username">root</property> <property name="connection. password"></property> <!-- JDBC connection pool (use the built-in) --> <property name="hibernate. connection. pool_size">10</property> <!-- My. SQL dialect//different for different Database --> <property name="dialect">org. hibernate. dialect. My. SQLDialect</property> <!-- Echo all executed SQL to stdout --> <property name="show_sql">true</property> <property name="hbm 2 ddl. auto">update</property> <mapping resource="Student. hbm. xml"/> </session-factory> </hibernate-configuration>
web-xml <? xml version="1. 0" encoding="UTF-8"? > <web-app version="2. 4" xmlns="http: //java. sun. com/xml/ns/j 2 ee" xmlns: xsi="http: //www. w 3. org/2001/XMLSchema-instance" xsi: schema. Location="http: //java. sun. com/xml/ns/j 2 ee/web-app_2_4. xsd"> <servlet> <servlet-name>Student. Info</servlet-name> <servlet-class>data. Student. Info. Servlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Student. Info</servlet-name> <url-pattern>/studentinfo</url-pattern> </servlet-mapping> </web-app>
- Slides: 68