Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For...

224
1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15 Derby 10.4.1.3 Tomcat 5.5.26 Eclipse 3.3.2 JEE Download and install the following: Hibernate 3.2.6 http://www.hibernate.org HibernateTools-3.2.2.Beta1.zip http://www.hibernate.org JDK 1.5.0.15 http://java.sun.com/javase/downloads/index_jdk5.jsp Derby 10.4.1.3 http://db.apache.org/derby Tomcat 5.5.26 http://www.apache.org Eclipse IDE for Java EE Developers http://www.eclipse.org/downloads/download.php?file=/technology/epp/downloads/releas e/europa/winter/eclipse-jee-europa-winter-win32.zip

Transcript of Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For...

Page 1: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

1

Hibernate Quick Start

For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15 Derby 10.4.1.3 Tomcat 5.5.26 Eclipse 3.3.2 JEE

Download and install the following:

Hibernate 3.2.6http://www.hibernate.org

HibernateTools-3.2.2.Beta1.ziphttp://www.hibernate.org

JDK 1.5.0.15http://java.sun.com/javase/downloads/index_jdk5.jsp

Derby 10.4.1.3http://db.apache.org/derby

Tomcat 5.5.26http://www.apache.org

Eclipse IDE for Java EE Developershttp://www.eclipse.org/downloads/download.php?file=/technology/epp/downloads/release/europa/winter/eclipse-jee-europa-winter-win32.zip

Page 2: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

2

Lab 1 - Prepare to Use Derby

Create a Desktop Shortcut to Start the Derby Database. Name the Shortcut Start Derby10.4.

Page 3: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

3

Update the Target value to:

C:\db-derby-10.4.1.3-bin\bin\startNetworkServer.bat

Page 4: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

4

Create another Desktop Shortcut to stop the Database.

Page 5: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

5

Update the Target value to:

C:\db-derby-10.4.1.3-bin\bin\stopNetworkServer.bat

Page 6: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

6

Start the Database Using the Desktop Shortcut

Double-click the Start Derby shortcut.

Page 7: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

7

Lab 2 - Install Hibernate Tools

This will add a new Perspective and a few nice features to Eclipse.

Make sure Eclipse is not running.

Extract the HibernateTools-3.2.2.Beta1.zip to a temporary directory.

Page 8: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

8

Copy the features and plugins folders to where Eclipse is installed.

Click Yes to All to replace.

Page 9: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

9

Lab 3 - Create the Eclipse Workspace and Server

Start Eclipse.

Create a new workspace called HibernateWorkspace

Page 10: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

10

Create a New Server

Select Window | Preferences…

Page 11: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

11

Select Server | Installed Runtimes

Click the Add… button.

Page 12: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

12

Select Tomcat v5.0, check the Also create new local server.

Page 13: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

13

Click the Browse… button.

Page 14: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

14

Select the Tomcat installation directory.

Page 15: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

15

Click Installed JREs… to select JRE 1.5.

Page 16: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

16

Click Add...

Page 17: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

17

Click Browse.

Page 18: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

18

Select jre1.5.0_15

Page 19: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

19

Click OK.

Page 20: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

20

Make this JRE the default and click OK.

Page 21: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

21

Click Finish.

Page 22: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

22

Click OK.

Page 23: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

23

Lab 4 - Create a New Dynamic Web Project and the Database

Select New | Project…

Select Web | Dynamic Web Project

Page 24: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

24

Name the project HibernateWebProject, click Next.

Page 25: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

25

Click Next.

Page 26: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

26

Click Finish.

Page 27: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

27

Create the Database

Open the Database Development Perspective.

Page 28: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

28

Select Database Development

Page 29: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

29

Create a New Database by selecting Databases | New…

Select Generic JDBC Connection

Page 30: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

30

Name the Database PetDB, click Next.

Page 31: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

31

Click the … button.

Page 32: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

32

Select Derby | 10.2, then click the Add… button.

Page 33: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

33

Select Derby Client JDBC Driver, click OK.

Page 34: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

34

Remove the JAR file.

Page 35: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

35

Click the Add Jar/Zip button.

Page 36: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

36

Select the derbyclient.jar file from where you installed Derbry \lib folder.

Page 37: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

37

Click OK.

Page 38: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

38

Click OK.

Page 39: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

39

Change the Database name to: PetDB.

Change the URL to: jdbc:derby://localhost:1527/PetDB;create=true

And the User name to user and Password to password

Page 40: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

40

Test the Connection.

Click Finish.

The database will be created by default in:

C:\db-derby-10.4.1.3-bin\bin

Page 41: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

41

Connect to the Database.

Page 42: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

42

Create a new SQL file.

Page 43: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

43

Name the file createPetDB and create it in HibernateWebProject.

Page 44: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

44

Add the following SQL. You can also copy the file from the Instructor.

DROP TABLE PET_NICKNAMES;DROP TABLE DOG;DROP TABLE INVENTORY;DROP TABLE PET;

CREATE TABLE PET(

PET_ID BIGINT NOT NULL GENERATED ALWAYS AS IDENTITY (STARTWITH 1, INCREMENT BY 1),

LICENSE VARCHAR(10) NOT NULL,NAME VARCHAR(40),DESCRIPTION VARCHAR(40),BIRTH_DATE DATE,PRICE DECIMAL(5,2),VERSION INTEGER DEFAULT 1,CONSTRAINT PK_PET PRIMARY KEY(PET_ID)

);

CREATE TABLE PET_NICKNAMES(

PET_ID BIGINT NOT NULL,NICKNAME VARCHAR(40) NOT NULL,CONSTRAINT PK_PET_BREEDS PRIMARY KEY(PET_ID, NICKNAME),CONSTRAINT FK_NICKNAMES_TO_PET FOREIGN KEY(PET_ID) REFERENCES

PET(PET_ID));

CREATE TABLE DOG(

PET_ID BIGINT NOT NULL,TRICKS VARCHAR(120) NOT NULL,CONSTRAINT PK_DOG PRIMARY KEY(PET_ID),CONSTRAINT FK_DOG_TO_PET FOREIGN KEY(PET_ID) REFERENCES

PET(PET_ID));

CREATE TABLE INVENTORY(

INVENTORY_ID BIGINT NOT NULL GENERATED ALWAYS AS IDENTITY (STARTWITH 1, INCREMENT BY 1),

PET_ID BIGINT NOT NULL,LOCATION VARCHAR(25) NOT NULL,QUANTITY INTEGER NOT NULL,VERSION INTEGER DEFAULT 1,CONSTRAINT PK_INVENTORY PRIMARY KEY(INVENTORY_ID),CONSTRAINT UNQ_PET_LOCATION UNIQUE(PET_ID, LOCATION),CONSTRAINT FK_INVENTORY_TO_PET FOREIGN KEY(PET_ID) REFERENCES

PET(PET_ID));

Page 45: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

45

INSERT INTO PET VALUES (DEFAULT, 'LIC00000', 'Fido', 'Dog', '1992-01-04', 19.95, 1);INSERT INTO PET VALUES (DEFAULT, 'LIC11111', 'Rex', 'Dog', '1994-02-05', 119.95, 1);INSERT INTO PET VALUES (DEFAULT, 'LIC12222', 'Fluffy', 'Cat', '1998-05-04', 29.95, 1);INSERT INTO PET VALUES (DEFAULT, 'LIC33333', 'Goldie', 'Fish', '2001-11-03', 39.95, 1);INSERT INTO PET VALUES (DEFAULT, 'LIC44444', 'Slinky', 'Snake', '2002-12-10', 49.95, 1);INSERT INTO PET VALUES (DEFAULT, 'LIC55555', 'Spot', 'Dog', '2004-06-15', 40.95, 1);INSERT INTO PET VALUES (DEFAULT, 'LIC66666', 'Inky', 'Cat', '2006-01-24', 110.95, 1);INSERT INTO PET VALUES (DEFAULT, 'LIC77777', 'Bubbles', 'Fish', '1992-02-14', 16.95, 1);INSERT INTO PET VALUES (DEFAULT, 'LIC88888', 'Arson', 'Dog', '1991-03-14', 10.95, 1);INSERT INTO PET VALUES (DEFAULT, 'LIC99999', 'Rollins', 'Dog', '1992-04-24', 120.95, 1);

INSERT INTO PET_NICKNAMES VALUES (1, 'Fi');INSERT INTO PET_NICKNAMES VALUES (1, 'Do');INSERT INTO PET_NICKNAMES VALUES (2, 'R');INSERT INTO PET_NICKNAMES VALUES (2, 'Rexxy');INSERT INTO PET_NICKNAMES VALUES (3, 'Fluf');INSERT INTO PET_NICKNAMES VALUES (4, 'Goldk');INSERT INTO PET_NICKNAMES VALUES (5, 'Slink');INSERT INTO PET_NICKNAMES VALUES (6, 'Out');INSERT INTO PET_NICKNAMES VALUES (7, 'Ink');INSERT INTO PET_NICKNAMES VALUES (8, 'Bub');INSERT INTO PET_NICKNAMES VALUES (9, 'Arny');INSERT INTO PET_NICKNAMES VALUES (10, 'Rolly');

INSERT INTO DOG VALUES (1, 'Sit, Play Dead');INSERT INTO DOG VALUES (2, 'Sit, Roll Over');INSERT INTO DOG VALUES (3, 'Eat, Sleep');INSERT INTO DOG VALUES (4, 'Eat, Swim');INSERT INTO DOG VALUES (5, 'Sleep, Eat');

INSERT INTO INVENTORY VALUES (DEFAULT, 1, 'Dallas', 10, 1);INSERT INTO INVENTORY VALUES (DEFAULT, 1, 'Ft Worth', 20, 1);INSERT INTO INVENTORY VALUES (DEFAULT, 2, 'Dallas', 15, 1);INSERT INTO INVENTORY VALUES (DEFAULT, 3, 'Dallas', 5, 1);INSERT INTO INVENTORY VALUES (DEFAULT, 4, 'Dallas', 8, 1);INSERT INTO INVENTORY VALUES (DEFAULT, 5, 'Dallas', 18, 1);INSERT INTO INVENTORY VALUES (DEFAULT, 6, 'Dallas', 3, 1);INSERT INTO INVENTORY VALUES (DEFAULT, 7, 'Dallas', 21, 1);INSERT INTO INVENTORY VALUES (DEFAULT, 8, 'Dallas', 4, 1);INSERT INTO INVENTORY VALUES (DEFAULT, 9, 'Dallas', 2, 1);INSERT INTO INVENTORY VALUES (DEFAULT, 10, 'Dallas', 1, 1);

Page 46: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

46

Set the Connection Profile Type, Name and Database.

Page 47: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

47

Execute the SQL. The DROP statements will fail, so select all of the SQL except theDROP statements and select Execute Selected Text.

Page 48: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

48

You should see the following Successful messages.

Page 49: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

49

You can examine and edit the data. You may have to refresh the database to see thetables.

Page 50: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

50

You can edit the data if you want to.

Click F5 to Refresh the data.

Page 51: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

51

Lab 5 - Prepare the Project for Hibernate.

Create a User Library.

Switch back to the JEE Perspective.

Page 52: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

52

Select Java | Build Path | User Libraries

Click New…

Page 53: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

53

Name the Library.

Page 54: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

54

Click Add JARs…

Page 55: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

55

Add the hibernate3.jar file from C:\hibernate-3.2

Page 56: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

56

Add the following JARs from C:\hibernate-3.2\lib

Page 57: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

57

Add derbyclient.jar from C:\db-derby-10.4.1.3-bin\lib

Page 58: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

58

Click OK

Page 59: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

59

Add the User Library to the Project.

Select the Project Properties

Page 60: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

60

Select Java Build Path | Libraries tab.

Click Add Library…

Page 61: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

61

Select User Library.

Page 62: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

62

Select the Library.

Page 63: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

63

Click OK.

Page 64: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

64

Create the Hibernate Configuration File

Create a new XML file in the src folder.

Page 65: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

65

Name the file hibernate.cfg.xml.

Page 66: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

66

Select to create the XML from a DTD file.

Page 67: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

67

Select the Hibernate DTD. This is available when Hibernate Tools is installed.

Page 68: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

68

Accept the defaults and click Finish.

Page 69: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

69

Enter the following.

<?xml version="1.0" encoding="utf-8"?><!DOCTYPE hibernate-configuration PUBLIC

"-//Hibernate/Hibernate Configuration DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

<!-- SessionFactory --><session-factory>

<!-- Properties --><property name="hibernate.connection.url">

jdbc:derby://localhost:1527/PetDB</property><property name="hibernate.connection.driver_class">

org.apache.derby.jdbc.ClientDriver</property><property name="hibernate.dialect">

org.hibernate.dialect.DerbyDialect</property><property name="hibernate.connection.pool_size">

1</property><property name="hibernate.connection.username">

user</property><property name="hibernate.connection.password">

password</property>

</session-factory>

</hibernate-configuration>

Page 70: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

70

Create a new package called tests.

Page 71: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

71

Create a new class called TestHibernate with the following attributes.

Page 72: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

72

Add the following code.

package tests;

import org.hibernate.HibernateException;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;

public class TestHibernate {

/*** @param args*/

public static void main(String[] args) {SessionFactory sf = null;Session s = null;

try {sf = new Configuration().

configure().buildSessionFactory();s = sf.openSession();s.beginTransaction();System.out.println(

"Session connect status: " + s.isConnected());

s.getTransaction().commit();} catch (HibernateException e) {

e.printStackTrace();} catch (Exception ex) {

ex.printStackTrace();} finally {

s.close();sf.close();

}

}

}

Page 73: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

73

Run the Test as a Java Application.

You should see the following results.

INFO: Not binding factory to JNDI, no JNDI name configuredSession connect status: trueSep 24, 2008 12:10:15 PM org.hibernate.impl.SessionFactoryImpl closeINFO: closing

Page 74: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

74

The Problem with the Classpath. This means that the JAR files will not be added to theserver. We will discuss this later.

If you have problems with Hibernate not finding the tables, try the following inhibernate.cfg.xml:

<property name="hibernate.default_schema">user

</property>

Page 75: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

75

Lab 6 - Create a Simple Class Mapping

Create a new package named pets.

Page 76: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

76

Create a new class named Pet with the following attributes.

Page 77: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

77

Add the following code.

package pets;

import java.io.Serializable;import java.math.BigDecimal;import java.sql.Date;

public class Pet implements Serializable {

private Long pet_id;private String license;private String name;private String description;private Date birth_date;private BigDecimal price;

public Long getPet_id() {return pet_id;

}

public void setPet_id(Long pet_id) {this.pet_id = pet_id;

}

public String getLicense() {return license;

}

public void setLicense(String license) {this.license = license;

}

public String getName() {return name;

}

public void setName(String name) {this.name = name;

}

public String getDescription() {return description;

}

public void setDescription(String description) {this.description = description;

}

Page 78: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

78

public Date getBirth_date() {return birth_date;

}

public void setBirth_date(Date birth_date) {this.birth_date = birth_date;

}

public BigDecimal getPrice() {return price;

}

public void setPrice(BigDecimal price) {this.price = price;

}

public Pet() {super();

}

public Pet(Long pet_id, String license,String name, String description,Date birth_date, BigDecimal price) {

this();this.pet_id = pet_id;this.license = license;this.name = name;this.description = description;this.birth_date = birth_date;this.price = price;

}

Page 79: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

79

public boolean equals(Object that) {if (this == that) {

return true;} else if (!(that instanceof Pet)) {

return false;} else {

return ((Pet) that).getPet_id().equals(this.getPet_id());

}}

public int hashCode() {return getPet_id().hashCode();

}

public String toString() {return super.toString() + ", " +

"Pet_ID: " + getPet_id() + ", " +"Name: " + getName() + ", " +"Description: " + getDescription() + ", " +"Price: " + getPrice() + ", " +"Date of Birth: " + getBirth_date();

}

}

Page 80: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

80

Create a new package named resources.

Page 81: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

81

Create the following XML file called Pet.hbm.xml in the package resources.

You can use the wizard and select the Mapping DTD.

Page 82: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

82

Enter the following.

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" ><hibernate-mapping>

<class name="pets.Pet" table="PET"><id name="pet_id" type="long" column="PET_ID">

<generator class="identity"/></id><property name="license" type="string" column="LICENSE"/><property name="name" type="string" column="NAME"/><property name="description" type="string"

column="DESCRIPTION"/><property name="birth_date" type="date" column="BIRTH_DATE"/><property name="price" type="big_decimal" column="PRICE"/>

</class>

</hibernate-mapping>

Page 83: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

83

Update hibernate.cfg.xml

<?xml version="1.0" encoding="utf-8"?><!DOCTYPE hibernate-configuration PUBLIC

"-//Hibernate/Hibernate Configuration DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

<!-- SessionFactory --><session-factory>

<!-- Properties --><property name="hibernate.connection.url">

jdbc:derby://localhost:1527/PetDB</property><property name="hibernate.connection.driver_class">

org.apache.derby.jdbc.ClientDriver</property><property name="hibernate.dialect">

org.hibernate.dialect.DerbyDialect</property><property name="hibernate.connection.pool_size">

1</property><property name="hibernate.connection.username">

user</property><property name="hibernate.connection.password">

password</property>

<!-- Mapping Files --><mapping resource="resources/Pet.hbm.xml"/>

</session-factory>

</hibernate-configuration>

Page 84: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

84

Create a new class called TestSimpleMapping and add the following code. You can alsocopy TestHibernate and paste it with the new name.

package tests;

import org.hibernate.HibernateException;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;

import pets.Pet;

public class TestSimpleMapping {

/*** @param args*/

public static void main(String[] args) {SessionFactory sf = null;Session s = null;

try {sf = new Configuration().

configure().buildSessionFactory();s = sf.openSession();s.beginTransaction();System.out.println(

"Session connect status: " + s.isConnected());

//Get a Pet from the DatabaseLong pet_id = new Long(1);Pet pet1 = (Pet) s.get(Pet.class, pet_id);System.out.println(pet1);

s.getTransaction().commit();} catch (HibernateException e) {

e.printStackTrace();} catch (Exception ex) {

ex.printStackTrace();} finally {

s.close();sf.close();

}

}

}

Page 85: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

85

Run the Test as a Java Application. You should see the following.

INFO: Not binding factory to JNDI, no JNDI name configuredSession connect status: truepets.Pet@1, Pet_ID: 1, Name: Fido, Description: Dog, Price: 19.95, Dateof Birth: 1992-01-04Sep 26, 2008 9:19:11 PM org.hibernate.impl.SessionFactoryImpl close

Page 86: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

86

Lab 7 - Logging with hibernate.show.sql

Add the following to hibernate.cfg.xml.

<?xml version="1.0" encoding="utf-8"?><!DOCTYPE hibernate-configuration PUBLIC

"-//Hibernate/Hibernate Configuration DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

<!-- SessionFactory --><session-factory>

<!-- Properties --><property name="hibernate.connection.url">

jdbc:derby://localhost:1527/PetDB</property><property name="hibernate.connection.driver_class">

org.apache.derby.jdbc.ClientDriver</property><property name="hibernate.dialect">

org.hibernate.dialect.DerbyDialect</property><property name="hibernate.connection.pool_size">

1</property><property name="hibernate.connection.username">

user</property><property name="hibernate.connection.password">

password</property>

<!-- Echo SQL --><property name="hibernate.show_sql">

True</property>

<!-- Mapping Files --><mapping resource="resources/Pet.hbm.xml"/>

</session-factory>

</hibernate-configuration>

Page 87: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

87

Re-Run TestSimpleMapping and you should see the following.

INFO: Not binding factory to JNDI, no JNDI name configuredSession connect status: trueHibernate: select pet0_.PET_ID as PET1_0_0_, pet0_.LICENSE asLICENSE0_0_, pet0_.NAME as NAME0_0_, pet0_.DESCRIPTION asDESCRIPT4_0_0_, pet0_.BIRTH_DATE as BIRTH5_0_0_, pet0_.PRICE asPRICE0_0_ from PET pet0_ where pet0_.PET_ID=?pets.Pet@1, Pet_ID: 1, Name: Fido, Description: Dog, Price: 19.95, Dateof Birth: 1992-01-04Sep 26, 2008 9:22:53 PM org.hibernate.impl.SessionFactoryImpl close

Page 88: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

88

Lab 8 - Logging with Log4j

Create a new file in the src folder called log4j.properties.

Page 89: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

89

Enter the following or copy the Hibernate sample and make any changes.

### direct log messages to stdout ###log4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.Target=System.outlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p%c{1}:%L - %m%n

### direct messages to file hibernate.log ####log4j.appender.file=org.apache.log4j.FileAppender#log4j.appender.file.File=hibernate.log#log4j.appender.file.layout=org.apache.log4j.PatternLayout#log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L- %m%n

### set log levels - for more verbose logging change 'info' to 'debug'###

log4j.rootLogger=warn, stdoutlog4j.logger.org.hibernate=info#log4j.logger.org.hibernate=debug

### log HQL query parser activity#log4j.logger.org.hibernate.hql.ast.AST=debug

### log just the SQLlog4j.logger.org.hibernate.SQL=debug

### log JDBC bind parameters ####log4j.logger.org.hibernate.type=infolog4j.logger.org.hibernate.type=debug

### log schema export/update ###log4j.logger.org.hibernate.tool.hbm2ddl=debug

### log HQL parse trees#log4j.logger.org.hibernate.hql=debug

### log cache activity ####log4j.logger.org.hibernate.cache=debug

### log transaction activity#log4j.logger.org.hibernate.transaction=debug

### log JDBC resource acquisition#log4j.logger.org.hibernate.jdbc=debug

### enable the following line if you want to track down connection ###### leakages when using DriverManagerConnectionProvider ####log4j.logger.org.hibernate.connection.DriverManagerConnectionProvider=trace

Page 90: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

90

Add the Log4j JAR file to the User Library.

Select Window | Preferences…

Page 91: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

91

From the Java Build Path | User Libraries, click the Add JARs… button.

Page 92: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

92

From the lib folder where you installed Hibernate, select log4j-1.2.11.jar and clickOpen.

Page 93: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

93

Click OK.

Page 94: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

94

Run TestSimpleMapping and you should see the following:

21:28:24,250 INFO SessionFactoryObjectFactory:82 - Not binding factoryto JNDI, no JNDI name configuredSession connect status: true21:28:24,296 DEBUG SQL:401 - select pet0_.PET_ID as PET1_0_0_,pet0_.LICENSE as LICENSE0_0_, pet0_.NAME as NAME0_0_, pet0_.DESCRIPTIONas DESCRIPT4_0_0_, pet0_.BIRTH_DATE as BIRTH5_0_0_, pet0_.PRICE asPRICE0_0_ from PET pet0_ where pet0_.PET_ID=?Hibernate: select pet0_.PET_ID as PET1_0_0_, pet0_.LICENSE asLICENSE0_0_, pet0_.NAME as NAME0_0_, pet0_.DESCRIPTION asDESCRIPT4_0_0_, pet0_.BIRTH_DATE as BIRTH5_0_0_, pet0_.PRICE asPRICE0_0_ from PET pet0_ where pet0_.PET_ID=?21:28:24,296 DEBUG LongType:133 - binding '1' to parameter: 121:28:24,328 DEBUG StringType:172 - returning 'LIC00000' as column:LICENSE0_0_21:28:24,328 DEBUG StringType:172 - returning 'Fido' as column:NAME0_0_21:28:24,328 DEBUG StringType:172 - returning 'Dog' as column:DESCRIPT4_0_0_21:28:24,343 DEBUG DateType:172 - returning '04 January 1992' ascolumn: BIRTH5_0_0_21:28:24,343 DEBUG BigDecimalType:172 - returning '19.95' as column:PRICE0_0_pets.Pet@1, Pet_ID: 1, Name: Fido, Description: Dog, Price: 19.95, Dateof Birth: 1992-01-0421:28:24,359 INFO SessionFactoryImpl:769 - closing

Page 95: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

95

Lab 9 - Simple Inserting and Modifying

Create a new class called TestSimpleInsertModify in the tests package.

Add the following code.

package tests;

import java.math.BigDecimal;import java.sql.Date;

import org.hibernate.HibernateException;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.cfg.Configuration;

import pets.Pet;

public class TestSimpleInsertModify {

public static void main(String[] args) {

SessionFactory sf = null;Session s = null;

try {sf = new Configuration().

configure().buildSessionFactory();s = sf.openSession();System.out.println(

"Session connect status: " + s.isConnected());

// Insert new PetPet pet1 = new Pet();pet1.setName("Rocky");pet1.setLicense("LIC12121");pet1.setDescription("Dog");pet1.setPrice(new BigDecimal("42.12"));pet1.setBirth_date(

new Date(System.currentTimeMillis()));

// Save the new PetTransaction tx = s.beginTransaction();Long pet1_id = (Long) s.save(pet1);System.out.println("Saved Pet: " + pet1);tx.commit();

Page 96: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

96

// Modify the Pettx = s.beginTransaction();pet1 = (Pet) s.get(Pet.class, pet1_id);System.out.println("Retrieved Pet: " + pet1);pet1.setDescription("This is a new Description");tx.commit();

// Deleting the Pettx = s.beginTransaction();pet1 = (Pet) s.load(Pet.class, pet1_id);s.delete(pet1);tx.commit();

} catch (HibernateException e) {e.printStackTrace();

} catch (Exception ex) {ex.printStackTrace();

} finally {s.close();sf.close();

}}

}

Page 97: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

97

Run the Test.

Session connect status: true21:49:16,156 DEBUG SQL:401 - insert into PET (PET_ID, LICENSE, NAME,DESCRIPTION, BIRTH_DATE, PRICE) values (default, ?, ?, ?, ?, ?)Hibernate: insert into PET (PET_ID, LICENSE, NAME, DESCRIPTION,BIRTH_DATE, PRICE) values (default, ?, ?, ?, ?, ?)21:49:16,171 DEBUG StringType:133 - binding 'LIC12121' to parameter: 121:49:16,171 DEBUG StringType:133 - binding 'Rocky' to parameter: 221:49:16,171 DEBUG StringType:133 - binding 'Dog' to parameter: 321:49:16,171 DEBUG DateType:133 - binding '26 September 2008' toparameter: 421:49:16,171 DEBUG BigDecimalType:133 - binding '42.12' to parameter: 521:49:16,187 DEBUG SQL:401 - values identity_val_local()Hibernate: values identity_val_local()Saved Pet: pets.Pet@b, Pet_ID: 11, Name: Rocky, Description: Dog,Price: 42.12, Date of Birth: 2008-09-26Retrieved Pet: pets.Pet@b, Pet_ID: 11, Name: Rocky, Description: Dog,Price: 42.12, Date of Birth: 2008-09-2621:49:16,218 DEBUG SQL:401 - update PET set LICENSE=?, NAME=?,DESCRIPTION=?, BIRTH_DATE=?, PRICE=? where PET_ID=?Hibernate: update PET set LICENSE=?, NAME=?, DESCRIPTION=?,BIRTH_DATE=?, PRICE=? where PET_ID=?21:49:16,250 DEBUG StringType:133 - binding 'LIC12121' to parameter: 121:49:16,250 DEBUG StringType:133 - binding 'Rocky' to parameter: 221:49:16,250 DEBUG StringType:133 - binding 'This is a new Description'to parameter: 321:49:16,250 DEBUG DateType:133 - binding '26 September 2008' toparameter: 421:49:16,250 DEBUG BigDecimalType:133 - binding '42.12' to parameter: 521:49:16,250 DEBUG LongType:133 - binding '11' to parameter: 621:49:16,265 DEBUG SQL:401 - delete from PET where PET_ID=?Hibernate: delete from PET where PET_ID=?21:49:16,265 DEBUG LongType:133 - binding '11' to parameter: 121:49:16,281 INFO SessionFactoryImpl:769 - closing

Page 98: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

98

Lab 10 - Simple HQL

Create a new class called TestSimpleHQL and add the following code.

package tests;

import java.math.BigDecimal;import java.sql.Date;import java.util.Iterator;

import org.hibernate.HibernateException;import org.hibernate.Query;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.cfg.Configuration;

import pets.Pet;

public class TestSimpleHQL {

public static void main(String[] args) {

SessionFactory sf = null;Session s = null;

try {sf = new Configuration().

configure().buildSessionFactory();s = sf.openSession();s.beginTransaction();System.out.println(

"Session connect status: " + s.isConnected());

// Simple QuerySystem.out.println(

"*** Query all Pets Where pet_id > 3 ***");Query q = s.createQuery("FROM Pet p WHERE pet_id > 3");Iterator i = q.list().iterator();while (i.hasNext()) {

Pet pet = (Pet) i.next();System.out.println(

"pet_id > 3 query retrieved Pet: " + pet);}

Page 99: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

99

// PagesSystem.out.println(

"*** Pagination - first 2 then next 2 where " +"pet_id > 3 ***");

q.setFirstResult(0);q.setMaxResults(2);System.out.println("--- First 2 results");i = q.list().iterator();while (i.hasNext()) {

Pet pet = (Pet) i.next();System.out.println(

"pet_id > 3 query retrieved Pet: " + pet);}

q.setFirstResult(5);q.setMaxResults(5);System.out.println("--- Second 2 results");i = q.list().iterator();while (i.hasNext()) {

Pet pet = (Pet) i.next();System.out.println(

"pet_id > 3 query retrieved Pet: " + pet);}

// Named ParametersSystem.out.println("*** Named Parameters **");Query q2 = s.createQuery("FROM Pet WHERE pet_id = :pet_id");q2.setLong("pet_id", new Long(4));Pet pet = (Pet) q2.uniqueResult();

System.out.println("Named Parameters query retrieved Pet: " + pet);

s.getTransaction().commit();

} catch (HibernateException e) {e.printStackTrace();

} catch (Exception ex) {ex.printStackTrace();

} finally {s.close();sf.close();

}}

}

Page 100: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

100

Add the following JAR file to the User Library.

Page 101: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

101

Run the Test and you should see the following.

Session connect status: true*** Query all Pets Where pet_id > 3 ***22:11:24,218 DEBUG SQL:401 - select pet0_.PET_ID as PET1_0_,pet0_.LICENSE as LICENSE0_, pet0_.NAME as NAME0_, pet0_.DESCRIPTION asDESCRIPT4_0_, pet0_.BIRTH_DATE as BIRTH5_0_, pet0_.PRICE as PRICE0_from PET pet0_ where pet0_.PET_ID>3Hibernate: select pet0_.PET_ID as PET1_0_, pet0_.LICENSE as LICENSE0_,pet0_.NAME as NAME0_, pet0_.DESCRIPTION as DESCRIPT4_0_,pet0_.BIRTH_DATE as BIRTH5_0_, pet0_.PRICE as PRICE0_ from PET pet0_where pet0_.PET_ID>322:11:24,234 DEBUG LongType:172 - returning '4' as column: PET1_0_22:11:24,234 DEBUG StringType:172 - returning 'LIC33333' as column:LICENSE0_22:11:24,234 DEBUG StringType:172 - returning 'Goldie' as column:NAME0_22:11:24,234 DEBUG StringType:172 - returning 'Fish' as column:DESCRIPT4_0_22:11:24,250 DEBUG DateType:172 - returning '03 November 2001' ascolumn: BIRTH5_0_22:11:24,250 DEBUG BigDecimalType:172 - returning '39.95' as column:PRICE0_22:11:24,250 DEBUG LongType:172 - returning '5' as column: PET1_0_22:11:24,250 DEBUG StringType:172 - returning 'LIC44444' as column:LICENSE0_22:11:24,250 DEBUG StringType:172 - returning 'Slinky' as column:NAME0_22:11:24,250 DEBUG StringType:172 - returning 'Snake' as column:DESCRIPT4_0_22:11:24,250 DEBUG DateType:172 - returning '10 December 2002' ascolumn: BIRTH5_0_22:11:24,250 DEBUG BigDecimalType:172 - returning '49.95' as column:PRICE0_22:11:24,250 DEBUG LongType:172 - returning '6' as column: PET1_0_22:11:24,250 DEBUG StringType:172 - returning 'LIC55555' as column:LICENSE0_22:11:24,250 DEBUG StringType:172 - returning 'Spot' as column: NAME0_22:11:24,250 DEBUG StringType:172 - returning 'Dog' as column:DESCRIPT4_0_22:11:24,250 DEBUG DateType:172 - returning '15 June 2004' as column:BIRTH5_0_22:11:24,250 DEBUG BigDecimalType:172 - returning '40.95' as column:PRICE0_22:11:24,250 DEBUG LongType:172 - returning '7' as column: PET1_0_22:11:24,265 DEBUG StringType:172 - returning 'LIC66666' as column:LICENSE0_22:11:24,265 DEBUG StringType:172 - returning 'Inky' as column: NAME0_22:11:24,265 DEBUG StringType:172 - returning 'Cat' as column:DESCRIPT4_0_

Page 102: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

102

22:11:24,265 DEBUG DateType:172 - returning '24 January 2006' ascolumn: BIRTH5_0_22:11:24,265 DEBUG BigDecimalType:172 - returning '110.95' as column:PRICE0_22:11:24,265 DEBUG LongType:172 - returning '8' as column: PET1_0_22:11:24,265 DEBUG StringType:172 - returning 'LIC77777' as column:LICENSE0_22:11:24,265 DEBUG StringType:172 - returning 'Bubbles' as column:NAME0_22:11:24,265 DEBUG StringType:172 - returning 'Fish' as column:DESCRIPT4_0_22:11:24,265 DEBUG DateType:172 - returning '14 February 1992' ascolumn: BIRTH5_0_22:11:24,265 DEBUG BigDecimalType:172 - returning '16.95' as column:PRICE0_22:11:24,265 DEBUG LongType:172 - returning '9' as column: PET1_0_22:11:24,265 DEBUG StringType:172 - returning 'LIC88888' as column:LICENSE0_22:11:24,265 DEBUG StringType:172 - returning 'Arson' as column: NAME0_22:11:24,265 DEBUG StringType:172 - returning 'Dog' as column:DESCRIPT4_0_22:11:24,265 DEBUG DateType:172 - returning '14 March 1991' as column:BIRTH5_0_22:11:24,265 DEBUG BigDecimalType:172 - returning '10.95' as column:PRICE0_22:11:24,265 DEBUG LongType:172 - returning '10' as column: PET1_0_22:11:24,265 DEBUG StringType:172 - returning 'LIC99999' as column:LICENSE0_22:11:24,265 DEBUG StringType:172 - returning 'Rollins' as column:NAME0_22:11:24,265 DEBUG StringType:172 - returning 'Dog' as column:DESCRIPT4_0_22:11:24,265 DEBUG DateType:172 - returning '24 April 1992' as column:BIRTH5_0_22:11:24,265 DEBUG BigDecimalType:172 - returning '120.95' as column:PRICE0_

Page 103: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

103

pet_id > 3 query retrieved Pet: pets.Pet@4, Pet_ID: 4, Name: Goldie,Description: Fish, Price: 39.95, Date of Birth: 2001-11-03pet_id > 3 query retrieved Pet: pets.Pet@5, Pet_ID: 5, Name: Slinky,Description: Snake, Price: 49.95, Date of Birth: 2002-12-10pet_id > 3 query retrieved Pet: pets.Pet@6, Pet_ID: 6, Name: Spot,Description: Dog, Price: 40.95, Date of Birth: 2004-06-15pet_id > 3 query retrieved Pet: pets.Pet@7, Pet_ID: 7, Name: Inky,Description: Cat, Price: 110.95, Date of Birth: 2006-01-24pet_id > 3 query retrieved Pet: pets.Pet@8, Pet_ID: 8, Name: Bubbles,Description: Fish, Price: 16.95, Date of Birth: 1992-02-14pet_id > 3 query retrieved Pet: pets.Pet@9, Pet_ID: 9, Name: Arson,Description: Dog, Price: 10.95, Date of Birth: 1991-03-14pet_id > 3 query retrieved Pet: pets.Pet@a, Pet_ID: 10, Name: Rollins,Description: Dog, Price: 120.95, Date of Birth: 1992-04-24*** Pagination - first 2 then next 2 where pet_id > 3 ***--- First 2 results22:11:24,281 DEBUG SQL:401 - select pet0_.PET_ID as PET1_0_,pet0_.LICENSE as LICENSE0_, pet0_.NAME as NAME0_, pet0_.DESCRIPTION asDESCRIPT4_0_, pet0_.BIRTH_DATE as BIRTH5_0_, pet0_.PRICE as PRICE0_from PET pet0_ where pet0_.PET_ID>3Hibernate: select pet0_.PET_ID as PET1_0_, pet0_.LICENSE as LICENSE0_,pet0_.NAME as NAME0_, pet0_.DESCRIPTION as DESCRIPT4_0_,pet0_.BIRTH_DATE as BIRTH5_0_, pet0_.PRICE as PRICE0_ from PET pet0_where pet0_.PET_ID>322:11:24,296 DEBUG LongType:172 - returning '4' as column: PET1_0_22:11:24,296 DEBUG LongType:172 - returning '5' as column: PET1_0_pet_id > 3 query retrieved Pet: pets.Pet@4, Pet_ID: 4, Name: Goldie,Description: Fish, Price: 39.95, Date of Birth: 2001-11-03pet_id > 3 query retrieved Pet: pets.Pet@5, Pet_ID: 5, Name: Slinky,Description: Snake, Price: 49.95, Date of Birth: 2002-12-10--- Second 2 results22:11:24,296 DEBUG SQL:401 - select pet0_.PET_ID as PET1_0_,pet0_.LICENSE as LICENSE0_, pet0_.NAME as NAME0_, pet0_.DESCRIPTION asDESCRIPT4_0_, pet0_.BIRTH_DATE as BIRTH5_0_, pet0_.PRICE as PRICE0_from PET pet0_ where pet0_.PET_ID>3Hibernate: select pet0_.PET_ID as PET1_0_, pet0_.LICENSE as LICENSE0_,pet0_.NAME as NAME0_, pet0_.DESCRIPTION as DESCRIPT4_0_,pet0_.BIRTH_DATE as BIRTH5_0_, pet0_.PRICE as PRICE0_ from PET pet0_where pet0_.PET_ID>322:11:24,296 DEBUG LongType:172 - returning '9' as column: PET1_0_22:11:24,296 DEBUG LongType:172 - returning '10' as column: PET1_0_pet_id > 3 query retrieved Pet: pets.Pet@9, Pet_ID: 9, Name: Arson,Description: Dog, Price: 10.95, Date of Birth: 1991-03-14pet_id > 3 query retrieved Pet: pets.Pet@a, Pet_ID: 10, Name: Rollins,Description: Dog, Price: 120.95, Date of Birth: 1992-04-24

Page 104: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

104

*** Named Parameters **22:11:24,312 DEBUG SQL:401 - select pet0_.PET_ID as PET1_0_,pet0_.LICENSE as LICENSE0_, pet0_.NAME as NAME0_, pet0_.DESCRIPTION asDESCRIPT4_0_, pet0_.BIRTH_DATE as BIRTH5_0_, pet0_.PRICE as PRICE0_from PET pet0_ where pet0_.PET_ID=?Hibernate: select pet0_.PET_ID as PET1_0_, pet0_.LICENSE as LICENSE0_,pet0_.NAME as NAME0_, pet0_.DESCRIPTION as DESCRIPT4_0_,pet0_.BIRTH_DATE as BIRTH5_0_, pet0_.PRICE as PRICE0_ from PET pet0_where pet0_.PET_ID=?22:11:24,312 DEBUG LongType:133 - binding '4' to parameter: 122:11:24,312 DEBUG LongType:172 - returning '4' as column: PET1_0_Named Parameters query retrieved Pet: pets.Pet@4, Pet_ID: 4, Name:Goldie, Description: Fish, Price: 39.95, Date of Birth: 2001-11-0322:11:24,328 INFO SessionFactoryImpl:769 - closing

Page 105: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

105

Lab 11 - Named Query

Update Pet.hbm.xml with the following Named Query.

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" ><hibernate-mapping>

<class name="pets.Pet" table="PET"><id name="pet_id" type="long" column="PET_ID">

<generator class="identity"/></id><property name="license" type="string" column="LICENSE"/><property name="name" type="string" column="NAME"/><property name="description" type="string"

column="DESCRIPTION"/><property name="birth_date" type="date" column="BIRTH_DATE"/><property name="price" type="big_decimal" column="PRICE"/>

</class>

<query name="Pet.findById"><![CDATA[FROM Pet WHERE pet_id = :id]]>

</query>

</hibernate-mapping>

Page 106: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

106

Create a new class named TestNamedQuery and add the following.

package tests;

import java.math.BigDecimal;import java.sql.Date;import java.util.Iterator;import org.hibernate.HibernateException;import org.hibernate.Query;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.cfg.Configuration;import pets.Pet;

public class TestNamedQuery {

public static void main(String[] args) {SessionFactory sf = null;Session s = null;try {

sf = new Configuration().configure().buildSessionFactory();

s = sf.openSession();s.beginTransaction();System.out.println(

"Session connect status: " + s.isConnected());

//Named QueryQuery q = s.getNamedQuery(

"Pet.findById");//Named Parameterq.setLong("id", 2);Iterator<Pet> i = q.list().iterator();System.out.println(

"Size " + q.list().size());while(i.hasNext()) {

Pet pet = i.next();System.out.println(pet);

}s.getTransaction().commit();} catch (HibernateException e) {

e.printStackTrace();} catch (Exception ex) {

ex.printStackTrace();} finally {

s.close();sf.close();

}}

}

Page 107: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

107

Run the Test.

Session connect status: true07:40:44,000 DEBUG SQL:401 - select pet0_.PET_ID as PET1_0_,pet0_.LICENSE as LICENSE0_, pet0_.NAME as NAME0_, pet0_.DESCRIPTION asDESCRIPT4_0_, pet0_.BIRTH_DATE as BIRTH5_0_, pet0_.PRICE as PRICE0_from PET pet0_ where pet0_.PET_ID=?Hibernate: select pet0_.PET_ID as PET1_0_, pet0_.LICENSE as LICENSE0_,pet0_.NAME as NAME0_, pet0_.DESCRIPTION as DESCRIPT4_0_,pet0_.BIRTH_DATE as BIRTH5_0_, pet0_.PRICE as PRICE0_ from PET pet0_where pet0_.PET_ID=?07:40:44,187 DEBUG LongType:133 - binding '2' to parameter: 107:40:44,203 DEBUG LongType:172 - returning '2' as column: PET1_0_07:40:44,218 DEBUG StringType:172 - returning 'LIC11111' as column:LICENSE0_07:40:44,218 DEBUG StringType:172 - returning 'Rex' as column: NAME0_07:40:44,218 DEBUG StringType:172 - returning 'Dog' as column:DESCRIPT4_0_07:40:44,218 DEBUG DateType:172 - returning '05 February 1994' ascolumn: BIRTH5_0_07:40:44,234 DEBUG BigDecimalType:172 - returning '119.95' as column:PRICE0_07:40:44,250 DEBUG SQL:401 - select pet0_.PET_ID as PET1_0_,pet0_.LICENSE as LICENSE0_, pet0_.NAME as NAME0_, pet0_.DESCRIPTION asDESCRIPT4_0_, pet0_.BIRTH_DATE as BIRTH5_0_, pet0_.PRICE as PRICE0_from PET pet0_ where pet0_.PET_ID=?Hibernate: select pet0_.PET_ID as PET1_0_, pet0_.LICENSE as LICENSE0_,pet0_.NAME as NAME0_, pet0_.DESCRIPTION as DESCRIPT4_0_,pet0_.BIRTH_DATE as BIRTH5_0_, pet0_.PRICE as PRICE0_ from PET pet0_where pet0_.PET_ID=?07:40:44,250 DEBUG LongType:133 - binding '2' to parameter: 107:40:44,250 DEBUG LongType:172 - returning '2' as column: PET1_0_Size 1pets.Pet@2, Pet_ID: 2, Name: Rex, Description: Dog, Price: 119.95, Dateof Birth: 1994-02-0507:40:44,265 INFO SessionFactoryImpl:769 - closing

Page 108: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

108

Lab 12 - Projection Query

Create a new classed named TestProjectionQuery and enter the following.

package tests;

import java.math.BigDecimal;import java.sql.Date;import java.util.Iterator;

import org.hibernate.HibernateException;import org.hibernate.Query;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.cfg.Configuration;

import pets.Pet;

public class TestProjectionQuery {

public static void main(String[] args) {

SessionFactory sf = null;Session s = null;

try {sf = new Configuration().

configure().buildSessionFactory();s = sf.openSession();s.beginTransaction();System.out.println(

"Session connect status: " + s.isConnected());

//Simple Projection QueryQuery q = s.createQuery("SELECT p.name FROM Pet p");

Iterator<String> i = q.list().iterator();System.out.println("Size " + q.list().size());while(i.hasNext()) {

System.out.println(i.next());}

Page 109: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

109

//More Projection QueryQuery q2 = s.createQuery(

"SELECT p.name, p.price FROM Pet p");

Iterator<Object[]> i2 = q2.list().iterator();System.out.println("Size " + q2.list().size());while(i2.hasNext()) {

Object[] object = i2.next();for(int k = 0; k < object.length; k++) {

System.out.println(object[k]);}

}

s.getTransaction().commit();

} catch (HibernateException e) {e.printStackTrace();

} catch (Exception ex) {ex.printStackTrace();

} finally {s.close();sf.close();

}}

}

Page 110: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

110

Run the Test and you should see the following results.

Session connect status: true07:46:17,796 DEBUG SQL:401 - select pet0_.NAME as col_0_0_ from PETpet0_Hibernate: select pet0_.NAME as col_0_0_ from PET pet0_07:46:17,812 DEBUG StringType:172 - returning 'Fido' as column:col_0_0_07:46:17,812 DEBUG StringType:172 - returning 'Rex' as column: col_0_0_07:46:17,812 DEBUG StringType:172 - returning 'Fluffy' as column:col_0_0_07:46:17,812 DEBUG StringType:172 - returning 'Goldie' as column:col_0_0_07:46:17,812 DEBUG StringType:172 - returning 'Slinky' as column:col_0_0_07:46:17,812 DEBUG StringType:172 - returning 'Spot' as column:col_0_0_07:46:17,812 DEBUG StringType:172 - returning 'Inky' as column:col_0_0_07:46:17,812 DEBUG StringType:172 - returning 'Bubbles' as column:col_0_0_07:46:17,812 DEBUG StringType:172 - returning 'Arson' as column:col_0_0_07:46:17,812 DEBUG StringType:172 - returning 'Rollins' as column:col_0_0_07:46:17,828 DEBUG SQL:401 - select pet0_.NAME as col_0_0_ from PETpet0_Hibernate: select pet0_.NAME as col_0_0_ from PET pet0_07:46:17,828 DEBUG StringType:172 - returning 'Fido' as column:col_0_0_07:46:17,828 DEBUG StringType:172 - returning 'Rex' as column: col_0_0_07:46:17,828 DEBUG StringType:172 - returning 'Fluffy' as column:col_0_0_07:46:17,828 DEBUG StringType:172 - returning 'Goldie' as column:col_0_0_07:46:17,828 DEBUG StringType:172 - returning 'Slinky' as column:col_0_0_07:46:17,828 DEBUG StringType:172 - returning 'Spot' as column:col_0_0_07:46:17,828 DEBUG StringType:172 - returning 'Inky' as column:col_0_0_07:46:17,828 DEBUG StringType:172 - returning 'Bubbles' as column:col_0_0_07:46:17,828 DEBUG StringType:172 - returning 'Arson' as column:col_0_0_07:46:17,828 DEBUG StringType:172 - returning 'Rollins' as column:col_0_0_

Page 111: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

111

Size 10FidoRexFluffyGoldieSlinkySpotInkyBubblesArsonRollins07:46:17,828 DEBUG SQL:401 - select pet0_.NAME as col_0_0_, pet0_.PRICEas col_1_0_ from PET pet0_Hibernate: select pet0_.NAME as col_0_0_, pet0_.PRICE as col_1_0_ fromPET pet0_07:46:17,843 DEBUG StringType:172 - returning 'Fido' as column:col_0_0_07:46:17,843 DEBUG BigDecimalType:172 - returning '19.95' as column:col_1_0_07:46:17,859 DEBUG StringType:172 - returning 'Rex' as column: col_0_0_07:46:17,859 DEBUG BigDecimalType:172 - returning '119.95' as column:col_1_0_07:46:17,859 DEBUG StringType:172 - returning 'Fluffy' as column:col_0_0_07:46:17,859 DEBUG BigDecimalType:172 - returning '29.95' as column:col_1_0_07:46:17,859 DEBUG StringType:172 - returning 'Goldie' as column:col_0_0_07:46:17,859 DEBUG BigDecimalType:172 - returning '39.95' as column:col_1_0_07:46:17,859 DEBUG StringType:172 - returning 'Slinky' as column:col_0_0_07:46:17,859 DEBUG BigDecimalType:172 - returning '49.95' as column:col_1_0_07:46:17,859 DEBUG StringType:172 - returning 'Spot' as column:col_0_0_07:46:17,859 DEBUG BigDecimalType:172 - returning '40.95' as column:col_1_0_07:46:17,859 DEBUG StringType:172 - returning 'Inky' as column:col_0_0_07:46:17,859 DEBUG BigDecimalType:172 - returning '110.95' as column:col_1_0_07:46:17,859 DEBUG StringType:172 - returning 'Bubbles' as column:col_0_0_

Page 112: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

112

07:46:17,859 DEBUG BigDecimalType:172 - returning '16.95' as column:col_1_0_07:46:17,859 DEBUG StringType:172 - returning 'Arson' as column:col_0_0_07:46:17,859 DEBUG BigDecimalType:172 - returning '10.95' as column:col_1_0_07:46:17,859 DEBUG StringType:172 - returning 'Rollins' as column:col_0_0_07:46:17,859 DEBUG BigDecimalType:172 - returning '120.95' as column:col_1_0_07:46:17,859 DEBUG SQL:401 - select pet0_.NAME as col_0_0_, pet0_.PRICEas col_1_0_ from PET pet0_Hibernate: select pet0_.NAME as col_0_0_, pet0_.PRICE as col_1_0_ fromPET pet0_07:46:17,859 DEBUG StringType:172 - returning 'Fido' as column:col_0_0_07:46:17,859 DEBUG BigDecimalType:172 - returning '19.95' as column:col_1_0_07:46:17,859 DEBUG StringType:172 - returning 'Rex' as column: col_0_0_07:46:17,859 DEBUG BigDecimalType:172 - returning '119.95' as column:col_1_0_07:46:17,859 DEBUG StringType:172 - returning 'Fluffy' as column:col_0_0_07:46:17,859 DEBUG BigDecimalType:172 - returning '29.95' as column:col_1_0_07:46:17,859 DEBUG StringType:172 - returning 'Goldie' as column:col_0_0_07:46:17,859 DEBUG BigDecimalType:172 - returning '39.95' as column:col_1_0_07:46:17,859 DEBUG StringType:172 - returning 'Slinky' as column:col_0_0_07:46:17,859 DEBUG BigDecimalType:172 - returning '49.95' as column:col_1_0_07:46:17,859 DEBUG StringType:172 - returning 'Spot' as column:col_0_0_

Page 113: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

113

07:46:17,859 DEBUG BigDecimalType:172 - returning '40.95' as column:col_1_0_07:46:17,859 DEBUG StringType:172 - returning 'Inky' as column:col_0_0_07:46:17,859 DEBUG BigDecimalType:172 - returning '110.95' as column:col_1_0_07:46:17,859 DEBUG StringType:172 - returning 'Bubbles' as column:col_0_0_07:46:17,859 DEBUG BigDecimalType:172 - returning '16.95' as column:col_1_0_07:46:17,875 DEBUG StringType:172 - returning 'Arson' as column:col_0_0_07:46:17,875 DEBUG BigDecimalType:172 - returning '10.95' as column:col_1_0_07:46:17,875 DEBUG StringType:172 - returning 'Rollins' as column:col_0_0_07:46:17,875 DEBUG BigDecimalType:172 - returning '120.95' as column:col_1_0_Size 10Fido19.95Rex119.95Fluffy29.95Goldie39.95Slinky49.95Spot40.95Inky110.95Bubbles16.95Arson10.95Rollins120.9507:46:17,875 INFO SessionFactoryImpl:769 - closing

Page 114: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

114

Lab 13 - Aggregates

Create a new class named TestAggregateQueryand add the following code.

package tests;

import java.math.BigDecimal;import java.sql.Date;import java.util.Iterator;

import org.hibernate.HibernateException;import org.hibernate.Query;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.cfg.Configuration;

import pets.Pet;

public class TestAggregateQuery {

public static void main(String[] args) {

SessionFactory sf = null;Session s = null;

try {sf = new Configuration().

configure().buildSessionFactory();s = sf.openSession();s.beginTransaction();System.out.println(

"Session connect status: " + s.isConnected());

//Aggregate QueryQuery q = s.createQuery(

"SELECT count(*) FROM Pet p");Long count = (Long)q.uniqueResult();System.out.println("Row Count: " + count);

Page 115: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

115

//Another Aggregate QueryQuery q2 = s.createQuery(

"SELECT count(*), count(distinct p.name) " +"FROM Pet p");

Iterator<Object[]> i2 = q2.list().iterator();System.out.println("Size " + q2.list().size());while(i2.hasNext()) {

Object[] object = i2.next();for(int m = 0; m < object.length; m++) {

System.out.println(object[m]);}

}

s.getTransaction().commit();

} catch (HibernateException e) {e.printStackTrace();

} catch (Exception ex) {ex.printStackTrace();

} finally {s.close();sf.close();

}}

}

Page 116: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

116

Run the Test and you should see the following.

Session connect status: true07:50:43,437 DEBUG SQL:401 - select count(*) as col_0_0_ from PET pet0_Hibernate: select count(*) as col_0_0_ from PET pet0_07:50:43,500 DEBUG LongType:172 - returning '10' as column: col_0_0_Row Count: 1007:50:43,500 DEBUG SQL:401 - select count(*) as col_0_0_,count(distinct pet0_.NAME) as col_1_0_ from PET pet0_Hibernate: select count(*) as col_0_0_, count(distinct pet0_.NAME) ascol_1_0_ from PET pet0_07:50:43,562 DEBUG LongType:172 - returning '10' as column: col_0_0_07:50:43,562 DEBUG LongType:172 - returning '10' as column: col_1_0_07:50:43,562 DEBUG SQL:401 - select count(*) as col_0_0_,count(distinct pet0_.NAME) as col_1_0_ from PET pet0_Hibernate: select count(*) as col_0_0_, count(distinct pet0_.NAME) ascol_1_0_ from PET pet0_07:50:43,578 DEBUG LongType:172 - returning '10' as column: col_0_0_07:50:43,578 DEBUG LongType:172 - returning '10' as column: col_1_0_Size 1101007:50:43,578 INFO SessionFactoryImpl:769 – closing

Page 117: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

117

Lab 14 – Context Sessions

Create a new package named utils.

Page 118: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

118

Create a new class named HibernateUtil with the following attributes.

Page 119: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

119

Add the following code.

package utils;

import org.hibernate.*;import org.hibernate.cfg.*;

public class HibernateUtil {

private static final SessionFactory sessionFactory;

static {try {

// Create the SessionFactory// from hibernate.cfg.xmlsessionFactory = new Configuration().

configure().buildSessionFactory();} catch (Throwable ex) {

// Make sure you log the exception,// as it might be swallowedSystem.err.println(

"Initial SessionFactory creation failed." + ex);throw new ExceptionInInitializerError(ex);

}}

public static SessionFactory getSessionFactory() {return sessionFactory;

}

public HibernateUtil() {super();

}

}

Page 120: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

120

Update hibernate.cfg.xml.

<?xml version="1.0" encoding="utf-8"?><!DOCTYPE hibernate-configuration PUBLIC

"-//Hibernate/Hibernate Configuration DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

<!-- SessionFactory --><session-factory>

<!-- Properties --><property name="hibernate.connection.url">

jdbc:derby://localhost:1527/PetDB</property><property name="hibernate.connection.driver_class">

org.apache.derby.jdbc.ClientDriver</property><property name="hibernate.dialect">

org.hibernate.dialect.DerbyDialect</property><property name="hibernate.connection.pool_size">

1</property><property name="hibernate.connection.username">

user</property><property name="hibernate.connection.password">

password</property>

<!-- Echo SQL --><property name="hibernate.show_sql">

True</property>

<!-- Use Thread local contextual sessions --><property

name="hibernate.current_session_context_class">thread

</property>

<!-- Mapping Files --><mapping resource="resources/Pet.hbm.xml"/>

</session-factory>

</hibernate-configuration>

Page 121: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

121

Create a new class named TestContextualSession and add the following code.

package tests;

import org.hibernate.HibernateException;import org.hibernate.Session;import utils.HibernateUtil;

public class TestContextualSession {

/*** @param args*/

public static void main(String[] args) {

Session s;

try {s = HibernateUtil.getSessionFactory().

getCurrentSession();s.beginTransaction();

System.out.println("*** Session connect status: " + s.isConnected());

s.getTransaction().commit();System.out.println(

"After commit session open state = " + s.isOpen());

} catch (HibernateException e) {e.printStackTrace();

}catch (Exception ex) { ex.printStackTrace(); }

}

}

Page 122: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

122

Run the Test and you should see the following.

*** Session connect status: trueAfter commit session open state = false

Page 123: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

123

Lab 15 – Detached Objects and Versioning

Update the Pet class to include a version field and getters and setters.

private Integer version;

public Integer getVersion() {return version;

}

public void setVersion(Integer version) {this.version = version;

}

Page 124: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

124

Update Pet.hbm.xml.

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" ><hibernate-mapping>

<class name="pets.Pet" table="PET"><id name="pet_id" type="long" column="PET_ID">

<generator class="identity"/></id>

<version name="version" column="VERSION"type="integer"unsaved-value="negative">

</version>

<property name="license" type="string" column="LICENSE"/><property name="name" type="string" column="NAME"/><property name="description" type="string"

column="DESCRIPTION"/><property name="birth_date" type="date" column="BIRTH_DATE"/><property name="price" type="big_decimal" column="PRICE"/>

</class>

<query name="Pet.findById"><![CDATA[FROM Pet WHERE pet_id = :id]]>

</query>

</hibernate-mapping>

Page 125: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

125

Create a new class named TestVersioning and add the following code. This will throwan Exception.

package tests;

import org.hibernate.HibernateException;import org.hibernate.Session;import pets.Pet;import utils.HibernateUtil;

public class TestVersioning {

/*** @param args*/

public static void main(String[] args) {

Session s;

try {// Create a Pet and Detachs = HibernateUtil.getSessionFactory().

getCurrentSession();s.beginTransaction();Pet pet1 = (Pet)s.get(Pet.class,

new Long(2));s.getTransaction().commit();//The Session is closed, pet1 is detached

// Create an Exceptions = HibernateUtil.getSessionFactory().

getCurrentSession();s.beginTransaction();

// Get the SAME PetPet pet2 = (Pet)s.get(Pet.class,

new Long(2));pet2.setName("ERROR");s.getTransaction().commit();//The Session is closed

Page 126: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

126

// Change the Petpet1.setDescription("DETACHED EXAMPLE");

// Reattachs = HibernateUtil.getSessionFactory().

getCurrentSession();s.beginTransaction();

s.merge(pet1);s.getTransaction().commit();

} catch (HibernateException e) {e.printStackTrace();

}catch (Exception ex) { ex.printStackTrace(); }

}

}

Page 127: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

127

Run the Test and you should see the following Exception.

org.hibernate.StaleObjectStateException: Row was updated or deleted byanother transaction (or unsaved-value mapping was incorrect):[pets.Pet#2]

atorg.hibernate.event.def.DefaultMergeEventListener.entityIsDetached(DefaultMergeEventListener.java:261)

atorg.hibernate.event.def.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:120)

atorg.hibernate.event.def.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:53)

at org.hibernate.impl.SessionImpl.fireMerge(SessionImpl.java:677)at org.hibernate.impl.SessionImpl.merge(SessionImpl.java:661)at org.hibernate.impl.SessionImpl.merge(SessionImpl.java:665)at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown

Source)at java.lang.reflect.Method.invoke(Unknown Source)at

org.hibernate.context.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:301)

at $Proxy0.merge(Unknown Source)at tests.TestVersioning.main(TestVersioning.java:47)

Page 128: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

128

Lab 16 – Mapping a Simple Value Set

Update the Pet class to add the following field with getters and setters to support a Set onnicknames.

Import Set and HashSet from java.util.

private Set nicknames = new HashSet();

public Set getNicknames() {return nicknames;

}

public void setNicknames(Set nicknames) {this.nicknames = nicknames;

}

Page 129: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

129

Update Pet.hbm.xml to include the Collection of values.

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" ><hibernate-mapping>

<class name="pets.Pet" table="PET"><id name="pet_id" type="long" column="PET_ID">

<generator class="identity"/></id>

<version name="version" column="VERSION"type="integer"unsaved-value="negative">

</version>

<property name="license" type="string" column="LICENSE"/><property name="name" type="string" column="NAME"/><property name="description" type="string"

column="DESCRIPTION"/><property name="birth_date" type="date" column="BIRTH_DATE"/><property name="price" type="big_decimal" column="PRICE"/>

<set name="nicknames" table="PET_NICKNAMES"><key column="PET_ID"/><element type="string" column="NICKNAME"/>

</set>

</class>

<query name="Pet.findById"><![CDATA[FROM Pet WHERE pet_id = :id]]>

</query>

</hibernate-mapping>

Page 130: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

130

Create a new class named TestSimpleCollection and add the following code.

package tests;

import org.hibernate.HibernateException;import org.hibernate.Session;import org.hibernate.Transaction;

import pets.Pet;import utils.HibernateUtil;

public class TestSimpleCollection {

/*** @param args*/

public static void main(String[] args) {

try {// Get a Pet and NicknamesLong pet_id = new Long(1);Session s = HibernateUtil.getSessionFactory().

getCurrentSession();Transaction tx = s.beginTransaction();Pet pet = (Pet)s.get(Pet.class, pet_id);System.out.println("Number of Bicknames: " +

pet.getNicknames().size());for (Object name : pet.getNicknames()) {

System.out.println(name);}tx.commit();

} catch (HibernateException e) {e.printStackTrace();

}catch (Exception ex) { ex.printStackTrace(); }

}

}

Page 131: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

131

Run the Test and you see the following results.

Number of Bicknames: 2FiDo

Page 132: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

132

Lab 17 – Relationships

Create a new class called Inventory with the following attributes.

Page 133: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

133

Add the following code.

package pets;

import java.io.Serializable;

public class Inventory implements Serializable {

private Long inventory_id;private String location;private Integer quantity;private Integer version;private Pet pet;

public Long getInventory_id() {return inventory_id;

}

public void setInventory_id(Long inventory_id) {this.inventory_id = inventory_id;

}

public String getLocation() {return location;

}

public void setLocation(String location) {this.location = location;

}

public Integer getQuantity() {return quantity;

}

public void setQuantity(Integer quantity) {this.quantity = quantity;

}

public Integer getVersion() {return version;

}

public void setVersion(Integer version) {this.version = version;

}

Page 134: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

134

public Pet getPet() {return pet;

}

public void setPet(Pet pet) {this.pet = pet;

}

public Inventory() {super();

}

public Inventory(String location, Integer quantity) {this();this.location = location;this.quantity = quantity;

}

public boolean equals(Object that) {if (this == that)

return true;else if (!(that instanceof Inventory))

return false;else {

// cast to Inventoryfinal Inventory compare = (Inventory) that;if (!compare.getInventory_id().

equals(this.getInventory_id()))return false;

if (!compare.getLocation().equals(this.getLocation()))

return false;return true;

}}

Page 135: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

135

public String toString() {String comma = ", ";StringBuffer sb = new StringBuffer();sb.append("Inventory: ");sb.append(getPet().getPet_id());sb.append(comma);sb.append(getLocation());sb.append(comma);sb.append(getQuantity());return sb.toString();

}

public void add(int amt) {setQuantity(getQuantity() + amt);

}

public void sub(int amt) throws Exception {if (amt > getQuantity()){

throw new Exception(getLocation() +" only has " + getQuantity() +" copies of " + getPet().getPet_id());

}else{

setQuantity(getQuantity() - amt);}

}

}

Page 136: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

136

Create a new XML file in the resources package called Inventory.hbm.xml and add thefollowing.

<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC

"-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>

<class name="pets.Inventory" table="INVENTORY" >

<id name="inventory_id" column="INVENTORY_ID"access="field"><generator class="identity"/>

</id>

<version column="VERSION" name="version"type="integer" access="field"unsaved-value="negative"/>

<property name="location"/><property name="quantity"/>

<many-to-one name="pet" column="PET_ID"class="pets.Pet"/>

</class>

</hibernate-mapping>

Page 137: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

137

Update hibernate.cfg.xml for the new Mapping file.

<!-- Mapping Files --><mapping resource="resources/Pet.hbm.xml"/>

<mapping resource="resources/Inventory.hbm.xml"/>

Page 138: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

138

Update the Pet class with a field and a getter and setter to support the Inventory.

private Set inventoryRecords = new HashSet();

public Set getInventoryRecords() {return inventoryRecords;

}

public void setInventoryRecords(Set inventoryRecords) {this.inventoryRecords = inventoryRecords;

}

Add the following method to add to the Inventory.

public void addInventoryRecord(String location, int quantity) {Inventory inv = new Inventory(location,quantity);inv.setPet(this);getInventoryRecords().add(inv);

}

Page 139: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

139

Update Pet.hbm.xml to support the relationship.

<set name="inventoryRecords" inverse="true"cascade="all">

<key column="PET_ID"/><one-to-many class="pets.Inventory"/>

</set>

Page 140: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

140

Create a new class named TestRelationship and add the following code.

package tests;

import org.hibernate.HibernateException;import org.hibernate.Session;import org.hibernate.Transaction;

import pets.Pet;import utils.HibernateUtil;

public class TestRelationship {

/*** @param args*/

public static void main(String[] args) {

try {// Get a Pet and add to the InventoryLong pet_id = new Long(1);Session s = HibernateUtil.getSessionFactory().

getCurrentSession();Transaction tx = s.beginTransaction();Pet pet = (Pet)s.get(Pet.class, pet_id);pet.addInventoryRecord("San Antonio", 10);tx.commit();

} catch (HibernateException e) {e.printStackTrace();

}catch (Exception ex) { ex.printStackTrace(); }

}

}

Page 141: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

141

Run the Test.

Then check the results in the Database.

Page 142: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

142

Lab 18 – Querying Relationships

Create a new class named TestRelationshipQuery and add the following.

package tests;

import java.util.HashSet;import java.util.List;

import org.hibernate.HibernateException;import org.hibernate.Query;import org.hibernate.Session;import org.hibernate.Transaction;

import pets.Pet;import utils.HibernateUtil;

public class TestRelationshipQuery {

/*** @param args*/

public static void main(String[] args) {

try {// Get the Pet and Inventory RecordsLong id = new Long(1);Session s = HibernateUtil.getSessionFactory().

getCurrentSession();Transaction tx = s.beginTransaction();System.out.println(

"*** Retrieving with Session.get() ***");Pet pet = (Pet)s.get(Pet.class,id);for (Object cur : pet.getInventoryRecords()) {

System.out.println(cur);}tx.commit();System.out.println(

"*** END Retrieving with Session.get() ***");

Page 143: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

143

// LEFT JOIN FETCH querys = HibernateUtil.getSessionFactory().

getCurrentSession();tx = s.beginTransaction();System.out.println(

"*** Querying with LEFT JOIN FETCH ***");String query = "SELECT p FROM Pet p " +

"LEFT JOIN FETCH " +"p.inventoryRecords WHERE p.pet_id = :id";

Query q = s.createQuery(query);q.setLong("id",new Long(1));List l = q.list();System.out.println("Size of list = " + l.size());HashSet hs = new HashSet(l);System.out.println("Size of hashSet = " + hs.size());pet = (Pet)hs.iterator().next();for (Object cur : pet.getInventoryRecords()) {

System.out.println(cur);}tx.commit();System.out.println(

"*** END Querying with LEFT JOIN FETCH ***");

// Optional query to get locationss = HibernateUtil.getSessionFactory().

getCurrentSession();tx = s.beginTransaction();query = "SELECT i.location FROM Pet pi JOIN " +

"pi.inventoryRecords i where pi.id = :id";q = s.createQuery(query);q.setLong("id",new Long(1));System.out.println(

"*** Locations for Pet 1 ***");for (Object cur : q.list()) {

System.out.println(cur);}System.out.println(

"*** End Locations for Pet 1 ***");tx.commit();

} catch (HibernateException e) {e.printStackTrace();

}catch (Exception ex) { ex.printStackTrace(); }

}

}

Page 144: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

144

Run the Test and you should see the following.

*** Retrieving with Session.get() ***17:08:26,687 DEBUG SQL:401 - select pet0_.PET_ID as PET1_0_0_,pet0_.VERSION as VERSION0_0_, pet0_.LICENSE as LICENSE0_0_, pet0_.NAMEas NAME0_0_, pet0_.DESCRIPTION as DESCRIPT5_0_0_, pet0_.BIRTH_DATE asBIRTH6_0_0_, pet0_.PRICE as PRICE0_0_ from PET pet0_ wherepet0_.PET_ID=?Hibernate: select pet0_.PET_ID as PET1_0_0_, pet0_.VERSION asVERSION0_0_, pet0_.LICENSE as LICENSE0_0_, pet0_.NAME as NAME0_0_,pet0_.DESCRIPTION as DESCRIPT5_0_0_, pet0_.BIRTH_DATE as BIRTH6_0_0_,pet0_.PRICE as PRICE0_0_ from PET pet0_ where pet0_.PET_ID=?17:08:26,687 DEBUG LongType:133 - binding '1' to parameter: 117:08:26,703 DEBUG IntegerType:172 - returning '3' as column:VERSION0_0_17:08:26,703 DEBUG StringType:172 - returning 'LIC00000' as column:LICENSE0_0_17:08:26,703 DEBUG StringType:172 - returning 'Fido' as column:NAME0_0_17:08:26,703 DEBUG StringType:172 - returning 'Dog' as column:DESCRIPT5_0_0_17:08:26,718 DEBUG DateType:172 - returning '04 January 1992' ascolumn: BIRTH6_0_0_17:08:26,718 DEBUG BigDecimalType:172 - returning '19.95' as column:PRICE0_0_17:08:26,734 DEBUG SQL:401 - select inventoryr0_.PET_ID as PET5_1_,inventoryr0_.INVENTORY_ID as INVENTORY1_1_, inventoryr0_.INVENTORY_IDas INVENTORY1_2_0_, inventoryr0_.VERSION as VERSION2_0_,inventoryr0_.location as location2_0_, inventoryr0_.quantity asquantity2_0_, inventoryr0_.PET_ID as PET5_2_0_ from INVENTORYinventoryr0_ where inventoryr0_.PET_ID=?Hibernate: select inventoryr0_.PET_ID as PET5_1_,inventoryr0_.INVENTORY_ID as INVENTORY1_1_, inventoryr0_.INVENTORY_IDas INVENTORY1_2_0_, inventoryr0_.VERSION as VERSION2_0_,inventoryr0_.location as location2_0_, inventoryr0_.quantity asquantity2_0_, inventoryr0_.PET_ID as PET5_2_0_ from INVENTORYinventoryr0_ where inventoryr0_.PET_ID=?17:08:26,734 DEBUG LongType:133 - binding '1' to parameter: 117:08:26,750 DEBUG LongType:172 - returning '1' as column:INVENTORY1_2_0_17:08:26,750 DEBUG IntegerType:172 - returning '1' as column:VERSION2_0_17:08:26,750 DEBUG StringType:172 - returning 'Dallas' as column:location2_0_17:08:26,750 DEBUG IntegerType:172 - returning '10' as column:quantity2_0_17:08:26,750 DEBUG LongType:172 - returning '1' as column: PET5_2_0_17:08:26,750 DEBUG LongType:172 - returning '1' as column: PET5_1_17:08:26,750 DEBUG LongType:172 - returning '1' as column:

Page 145: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

145

INVENTORY1_1_17:08:26,750 DEBUG LongType:172 - returning '2' as column:INVENTORY1_2_0_17:08:26,750 DEBUG IntegerType:172 - returning '1' as column:VERSION2_0_17:08:26,750 DEBUG StringType:172 - returning 'Ft Worth' as column:location2_0_17:08:26,765 DEBUG IntegerType:172 - returning '20' as column:quantity2_0_17:08:26,765 DEBUG LongType:172 - returning '1' as column: PET5_2_0_17:08:26,765 DEBUG LongType:172 - returning '1' as column: PET5_1_17:08:26,765 DEBUG LongType:172 - returning '2' as column:INVENTORY1_1_17:08:26,765 DEBUG LongType:172 - returning '13' as column:INVENTORY1_2_0_17:08:26,765 DEBUG IntegerType:172 - returning '0' as column:VERSION2_0_17:08:26,765 DEBUG StringType:172 - returning 'San Antonio' as column:location2_0_17:08:26,765 DEBUG IntegerType:172 - returning '10' as column:quantity2_0_17:08:26,765 DEBUG LongType:172 - returning '1' as column: PET5_2_0_17:08:26,765 DEBUG LongType:172 - returning '1' as column: PET5_1_17:08:26,765 DEBUG LongType:172 - returning '13' as column:INVENTORY1_1_Inventory: 1, Ft Worth, 20Inventory: 1, San Antonio, 10Inventory: 1, Dallas, 10*** END Retrieving with Session.get() ****** Querying with LEFT JOIN FETCH ***17:08:26,812 DEBUG SQL:401 - select pet0_.PET_ID as PET1_0_0_,inventoryr1_.INVENTORY_ID as INVENTORY1_2_1_, pet0_.VERSION asVERSION0_0_, pet0_.LICENSE as LICENSE0_0_, pet0_.NAME as NAME0_0_,pet0_.DESCRIPTION as DESCRIPT5_0_0_, pet0_.BIRTH_DATE as BIRTH6_0_0_,pet0_.PRICE as PRICE0_0_, inventoryr1_.VERSION as VERSION2_1_,inventoryr1_.location as location2_1_, inventoryr1_.quantity asquantity2_1_, inventoryr1_.PET_ID as PET5_2_1_, inventoryr1_.PET_ID asPET5_0__, inventoryr1_.INVENTORY_ID as INVENTORY1_0__ from PET pet0_left outer join INVENTORY inventoryr1_ onpet0_.PET_ID=inventoryr1_.PET_ID where pet0_.PET_ID=?Hibernate: select pet0_.PET_ID as PET1_0_0_, inventoryr1_.INVENTORY_IDas INVENTORY1_2_1_, pet0_.VERSION as VERSION0_0_, pet0_.LICENSE asLICENSE0_0_, pet0_.NAME as NAME0_0_, pet0_.DESCRIPTION asDESCRIPT5_0_0_, pet0_.BIRTH_DATE as BIRTH6_0_0_, pet0_.PRICE asPRICE0_0_, inventoryr1_.VERSION as VERSION2_1_, inventoryr1_.locationas location2_1_, inventoryr1_.quantity as quantity2_1_,inventoryr1_.PET_ID as PET5_2_1_, inventoryr1_.PET_ID as PET5_0__,inventoryr1_.INVENTORY_ID as INVENTORY1_0__ from PET pet0_ left outerjoin INVENTORY inventoryr1_ on pet0_.PET_ID=inventoryr1_.PET_ID wherepet0_.PET_ID=?

Page 146: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

146

17:08:26,828 DEBUG LongType:133 - binding '1' to parameter: 117:08:26,843 DEBUG LongType:172 - returning '1' as column: PET1_0_0_17:08:26,843 DEBUG LongType:172 - returning '1' as column:INVENTORY1_2_1_17:08:26,843 DEBUG IntegerType:172 - returning '3' as column:VERSION0_0_17:08:26,843 DEBUG StringType:172 - returning 'LIC00000' as column:LICENSE0_0_17:08:26,843 DEBUG StringType:172 - returning 'Fido' as column:NAME0_0_17:08:26,843 DEBUG StringType:172 - returning 'Dog' as column:DESCRIPT5_0_0_17:08:26,843 DEBUG DateType:172 - returning '04 January 1992' ascolumn: BIRTH6_0_0_17:08:26,843 DEBUG BigDecimalType:172 - returning '19.95' as column:PRICE0_0_17:08:26,843 DEBUG IntegerType:172 - returning '1' as column:VERSION2_1_17:08:26,843 DEBUG StringType:172 - returning 'Dallas' as column:location2_1_17:08:26,843 DEBUG IntegerType:172 - returning '10' as column:quantity2_1_17:08:26,843 DEBUG LongType:172 - returning '1' as column: PET5_2_1_17:08:26,843 DEBUG LongType:172 - returning '1' as column: PET5_0__17:08:26,843 DEBUG LongType:172 - returning '1' as column:INVENTORY1_0__17:08:26,843 DEBUG LongType:172 - returning '1' as column: PET1_0_0_17:08:26,843 DEBUG LongType:172 - returning '2' as column:INVENTORY1_2_1_17:08:26,843 DEBUG IntegerType:172 - returning '1' as column:VERSION2_1_17:08:26,843 DEBUG StringType:172 - returning 'Ft Worth' as column:location2_1_17:08:26,843 DEBUG IntegerType:172 - returning '20' as column:quantity2_1_17:08:26,843 DEBUG LongType:172 - returning '1' as column: PET5_2_1_17:08:26,843 DEBUG LongType:172 - returning '1' as column: PET5_0__17:08:26,843 DEBUG LongType:172 - returning '2' as column:INVENTORY1_0__17:08:26,843 DEBUG LongType:172 - returning '1' as column: PET1_0_0_17:08:26,843 DEBUG LongType:172 - returning '13' as column:INVENTORY1_2_1_17:08:26,843 DEBUG IntegerType:172 - returning '0' as column:VERSION2_1_17:08:26,843 DEBUG StringType:172 - returning 'San Antonio' as column:location2_1_17:08:26,843 DEBUG IntegerType:172 - returning '10' as column:quantity2_1_17:08:26,843 DEBUG LongType:172 - returning '1' as column: PET5_2_1_17:08:26,843 DEBUG LongType:172 - returning '1' as column: PET5_0__17:08:26,843 DEBUG LongType:172 - returning '13' as column:INVENTORY1_0__

Page 147: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

147

Size of list = 3Size of hashSet = 1Inventory: 1, Ft Worth, 20Inventory: 1, San Antonio, 10Inventory: 1, Dallas, 10*** END Querying with LEFT JOIN FETCH ****** Locations for Pet 1 ***17:08:26,890 DEBUG SQL:401 - select inventoryr1_.location as col_0_0_from PET pet0_ inner join INVENTORY inventoryr1_ onpet0_.PET_ID=inventoryr1_.PET_ID where pet0_.PET_ID=?Hibernate: select inventoryr1_.location as col_0_0_ from PET pet0_inner join INVENTORY inventoryr1_ on pet0_.PET_ID=inventoryr1_.PET_IDwhere pet0_.PET_ID=?17:08:26,906 DEBUG LongType:133 - binding '1' to parameter: 117:08:26,906 DEBUG StringType:172 - returning 'Dallas' as column:col_0_0_17:08:26,906 DEBUG StringType:172 - returning 'Ft Worth' as column:col_0_0_17:08:26,906 DEBUG StringType:172 - returning 'San Antonio' as column:col_0_0_DallasFt WorthSan Antonio*** End Locations for Pet 1 ***

Page 148: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

148

Lab 19 – Inheritance

Create a new class named Dog with the following attributes.

Page 149: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

149

Add the following code.

package pets;

import java.math.BigDecimal;import java.sql.Date;

public class Dog extends Pet {

private String tricks;

public String getTricks() {return tricks;

}

public void setTricks(String tricks) {this.tricks = tricks;

}

public Dog() {super();

}

public Dog(Long pet_id, String license,String name, String description,Date birth_date, BigDecimal price) {

super(pet_id, license, name, description,birth_date, price);

}

@Overridepublic String toString() {

return super.toString() +"Tricks: " + getTricks();

}

}

Page 150: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

150

Update Pet.hbm.xml with the following.

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" ><hibernate-mapping>

<class name="pets.Pet" table="PET"><id name="pet_id" type="long" column="PET_ID">

<generator class="identity"/></id>

<version name="version" column="VERSION"type="integer"unsaved-value="negative">

</version>

<property name="license" type="string" column="LICENSE"/><property name="name" type="string" column="NAME"/><property name="description" type="string"

column="DESCRIPTION"/><property name="birth_date" type="date" column="BIRTH_DATE"/><property name="price" type="big_decimal" column="PRICE"/>

<set name="nicknames" table="PET_NICKNAMES"><key column="PET_ID"/><element type="string" column="NICKNAME"/>

</set>

<set name="inventoryRecords" inverse="true"cascade="all">

<key column="PET_ID"/><one-to-many class="pets.Inventory"/>

</set>

<joined-subclass name="pets.Dog" table="DOG"><key column="PET_ID"/><property name="tricks" column="TRICKS"/>

</joined-subclass>

</class>

<query name="Pet.findById"><![CDATA[FROM Pet WHERE pet_id = :id]]>

</query>

</hibernate-mapping>

Page 151: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

151

Create a new class named TestInheritance and add the following code.

package tests;

import java.util.HashSet;import java.util.Iterator;import java.util.List;

import org.hibernate.HibernateException;import org.hibernate.Query;import org.hibernate.Session;import org.hibernate.Transaction;

import utils.HibernateUtil;

public class TestInheritance {

/*** @param args*/

public static void main(String[] args) {

try {// Get the Pet and Inventory RecordsSession s = HibernateUtil.getSessionFactory().

getCurrentSession();Transaction tx = s.beginTransaction();System.out.println(

"*** Query all Pets and Dogs Where " +"pet_id < 10 ***");

Query q = s.createQuery("FROM Pet p WHERE pet_id < 10");

Iterator i = q.list().iterator();System.out.println(

"pet_id < 10 query retrieved Pets: ");while (i.hasNext()) {

System.out.println(i.next());}tx.commit();

} catch (HibernateException e) {e.printStackTrace();

}catch (Exception ex) { ex.printStackTrace(); }

}

}

Page 152: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

152

Run the Test and you should see the following results.

*** Query all Pets and Dogs Where pet_id < 10 ***21:59:21,734 DEBUG SQL:401 - select pet0_.PET_ID as PET1_0_,pet0_.VERSION as VERSION0_, pet0_.LICENSE as LICENSE0_, pet0_.NAME asNAME0_, pet0_.DESCRIPTION as DESCRIPT5_0_, pet0_.BIRTH_DATE asBIRTH6_0_, pet0_.PRICE as PRICE0_, pet0_1_.TRICKS as TRICKS2_, casewhen pet0_1_.PET_ID is not null then 1 when pet0_.PET_ID is not nullthen 0 else -1 end as clazz_ from PET pet0_ left outer join DOG pet0_1_on pet0_.PET_ID=pet0_1_.PET_ID where pet0_.PET_ID<10Hibernate: select pet0_.PET_ID as PET1_0_, pet0_.VERSION as VERSION0_,pet0_.LICENSE as LICENSE0_, pet0_.NAME as NAME0_, pet0_.DESCRIPTION asDESCRIPT5_0_, pet0_.BIRTH_DATE as BIRTH6_0_, pet0_.PRICE as PRICE0_,pet0_1_.TRICKS as TRICKS2_, case when pet0_1_.PET_ID is not null then 1when pet0_.PET_ID is not null then 0 else -1 end as clazz_ from PETpet0_ left outer join DOG pet0_1_ on pet0_.PET_ID=pet0_1_.PET_ID wherepet0_.PET_ID<1021:59:21,750 DEBUG LongType:172 - returning '1' as column: PET1_0_21:59:21,750 DEBUG IntegerType:172 - returning '1' as column: clazz_21:59:21,750 DEBUG IntegerType:172 - returning '3' as column: VERSION0_21:59:21,765 DEBUG StringType:172 - returning 'LIC00000' as column:LICENSE0_21:59:21,765 DEBUG StringType:172 - returning 'Fido' as column: NAME0_21:59:21,765 DEBUG StringType:172 - returning 'Dog' as column:DESCRIPT5_0_21:59:21,765 DEBUG DateType:172 - returning '04 January 1992' ascolumn: BIRTH6_0_21:59:21,765 DEBUG BigDecimalType:172 - returning '19.95' as column:PRICE0_21:59:21,765 DEBUG StringType:172 - returning 'Sit, Play Dead' ascolumn: TRICKS2_21:59:21,781 DEBUG LongType:172 - returning '2' as column: PET1_0_21:59:21,781 DEBUG IntegerType:172 - returning '1' as column: clazz_21:59:21,781 DEBUG IntegerType:172 - returning '2' as column: VERSION0_21:59:21,781 DEBUG StringType:172 - returning 'LIC11111' as column:LICENSE0_21:59:21,781 DEBUG StringType:172 - returning 'ERROR' as column: NAME0_21:59:21,781 DEBUG StringType:172 - returning 'Dog' as column:DESCRIPT5_0_21:59:21,781 DEBUG DateType:172 - returning '05 February 1994' ascolumn: BIRTH6_0_21:59:21,781 DEBUG BigDecimalType:172 - returning '119.95' as column:PRICE0_21:59:21,781 DEBUG StringType:172 - returning 'Sit, Roll Over' ascolumn: TRICKS2_21:59:21,781 DEBUG LongType:172 - returning '3' as column: PET1_0_21:59:21,781 DEBUG IntegerType:172 - returning '1' as column: clazz_21:59:21,781 DEBUG IntegerType:172 - returning '1' as column: VERSION0_21:59:21,781 DEBUG StringType:172 - returning 'LIC12222' as column:LICENSE0_

Page 153: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

153

21:59:21,781 DEBUG StringType:172 - returning 'Fluffy' as column:NAME0_21:59:21,781 DEBUG StringType:172 - returning 'Cat' as column:DESCRIPT5_0_21:59:21,781 DEBUG DateType:172 - returning '04 May 1998' as column:BIRTH6_0_21:59:21,781 DEBUG BigDecimalType:172 - returning '29.95' as column:PRICE0_21:59:21,781 DEBUG StringType:172 - returning 'Eat, Sleep' as column:TRICKS2_21:59:21,781 DEBUG LongType:172 - returning '4' as column: PET1_0_21:59:21,781 DEBUG IntegerType:172 - returning '1' as column: clazz_21:59:21,781 DEBUG IntegerType:172 - returning '1' as column: VERSION0_21:59:21,781 DEBUG StringType:172 - returning 'LIC33333' as column:LICENSE0_21:59:21,781 DEBUG StringType:172 - returning 'Goldie' as column:NAME0_21:59:21,781 DEBUG StringType:172 - returning 'Fish' as column:DESCRIPT5_0_21:59:21,796 DEBUG DateType:172 - returning '03 November 2001' ascolumn: BIRTH6_0_21:59:21,796 DEBUG BigDecimalType:172 - returning '39.95' as column:PRICE0_21:59:21,796 DEBUG StringType:172 - returning 'Eat, Swim' as column:TRICKS2_21:59:21,796 DEBUG LongType:172 - returning '5' as column: PET1_0_21:59:21,796 DEBUG IntegerType:172 - returning '1' as column: clazz_21:59:21,796 DEBUG IntegerType:172 - returning '1' as column: VERSION0_21:59:21,796 DEBUG StringType:172 - returning 'LIC44444' as column:LICENSE0_21:59:21,796 DEBUG StringType:172 - returning 'Slinky' as column:NAME0_21:59:21,796 DEBUG StringType:172 - returning 'Snake' as column:DESCRIPT5_0_21:59:21,796 DEBUG DateType:172 - returning '10 December 2002' ascolumn: BIRTH6_0_21:59:21,796 DEBUG BigDecimalType:172 - returning '49.95' as column:PRICE0_21:59:21,796 DEBUG StringType:172 - returning 'Sleep, Eat' as column:TRICKS2_21:59:21,796 DEBUG LongType:172 - returning '6' as column: PET1_0_21:59:21,796 DEBUG IntegerType:172 - returning '0' as column: clazz_21:59:21,796 DEBUG IntegerType:172 - returning '1' as column: VERSION0_21:59:21,796 DEBUG StringType:172 - returning 'LIC55555' as column:LICENSE0_21:59:21,796 DEBUG StringType:172 - returning 'Spot' as column: NAME0_21:59:21,796 DEBUG StringType:172 - returning 'Dog' as column:DESCRIPT5_0_21:59:21,796 DEBUG DateType:172 - returning '15 June 2004' as column:BIRTH6_0_

Page 154: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

154

21:59:21,796 DEBUG BigDecimalType:172 - returning '40.95' as column:PRICE0_21:59:21,796 DEBUG LongType:172 - returning '7' as column: PET1_0_21:59:21,796 DEBUG IntegerType:172 - returning '0' as column: clazz_21:59:21,796 DEBUG IntegerType:172 - returning '1' as column: VERSION0_21:59:21,796 DEBUG StringType:172 - returning 'LIC66666' as column:LICENSE0_21:59:21,796 DEBUG StringType:172 - returning 'Inky' as column: NAME0_21:59:21,796 DEBUG StringType:172 - returning 'Cat' as column:DESCRIPT5_0_21:59:21,796 DEBUG DateType:172 - returning '24 January 2006' ascolumn: BIRTH6_0_21:59:21,796 DEBUG BigDecimalType:172 - returning '110.95' as column:PRICE0_21:59:21,796 DEBUG LongType:172 - returning '8' as column: PET1_0_21:59:21,796 DEBUG IntegerType:172 - returning '0' as column: clazz_21:59:21,796 DEBUG IntegerType:172 - returning '1' as column: VERSION0_21:59:21,796 DEBUG StringType:172 - returning 'LIC77777' as column:LICENSE0_21:59:21,796 DEBUG StringType:172 - returning 'Bubbles' as column:NAME0_21:59:21,796 DEBUG StringType:172 - returning 'Fish' as column:DESCRIPT5_0_21:59:21,796 DEBUG DateType:172 - returning '14 February 1992' ascolumn: BIRTH6_0_21:59:21,796 DEBUG BigDecimalType:172 - returning '16.95' as column:PRICE0_21:59:21,796 DEBUG LongType:172 - returning '9' as column: PET1_0_21:59:21,796 DEBUG IntegerType:172 - returning '0' as column: clazz_21:59:21,796 DEBUG IntegerType:172 - returning '1' as column: VERSION0_21:59:21,796 DEBUG StringType:172 - returning 'LIC88888' as column:LICENSE0_21:59:21,796 DEBUG StringType:172 - returning 'Arson' as column: NAME0_21:59:21,796 DEBUG StringType:172 - returning 'Dog' as column:DESCRIPT5_0_21:59:21,796 DEBUG DateType:172 - returning '14 March 1991' as column:BIRTH6_0_21:59:21,812 DEBUG BigDecimalType:172 - returning '10.95' as column:PRICE0_

Page 155: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

155

pet_id < 10 query retrieved Pets:pets.Dog@1, Pet_ID: 1, Name: Fido, Description: Dog, Price: 19.95, Dateof Birth: 1992-01-04Tricks: Sit, Play Deadpets.Dog@2, Pet_ID: 2, Name: ERROR, Description: Dog, Price: 119.95,Date of Birth: 1994-02-05Tricks: Sit, Roll Overpets.Dog@3, Pet_ID: 3, Name: Fluffy, Description: Cat, Price: 29.95,Date of Birth: 1998-05-04Tricks: Eat, Sleeppets.Dog@4, Pet_ID: 4, Name: Goldie, Description: Fish, Price: 39.95,Date of Birth: 2001-11-03Tricks: Eat, Swimpets.Dog@5, Pet_ID: 5, Name: Slinky, Description: Snake, Price: 49.95,Date of Birth: 2002-12-10Tricks: Sleep, Eatpets.Pet@6, Pet_ID: 6, Name: Spot, Description: Dog, Price: 40.95, Dateof Birth: 2004-06-15pets.Pet@7, Pet_ID: 7, Name: Inky, Description: Cat, Price: 110.95,Date of Birth: 2006-01-24pets.Pet@8, Pet_ID: 8, Name: Bubbles, Description: Fish, Price: 16.95,Date of Birth: 1992-02-14pets.Pet@9, Pet_ID: 9, Name: Arson, Description: Dog, Price: 10.95,Date of Birth: 1991-03-14

Page 156: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

156

Lab 20 – Filter Query

Update Inventory.hbm.xml with the following.

<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC

"-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>

<class name="pets.Inventory" table="INVENTORY" >

<id name="inventory_id" column="INVENTORY_ID"access="field"><generator class="identity"/>

</id>

<version column="VERSION" name="version"type="integer" access="field"unsaved-value="negative"/>

<property name="location"/><property name="quantity"/>

<many-to-one name="pet" column="PET_ID"class="pets.Pet"/>

<filter name="byQuantity"condition="quantity >= :theQuantity"/>

</class>

<filter-def name="byQuantity"><filter-param name="theQuantity" type="integer"/>

</filter-def>

</hibernate-mapping>

Page 157: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

157

Create a new class named TestFilterQuery and add the following.

package tests;

import org.hibernate.HibernateException;import org.hibernate.Query;import org.hibernate.Session;import org.hibernate.Transaction;

import pets.Pet;import utils.HibernateUtil;

public class TestFilterQuery {

/*** @param args*/

public static void main(String[] args) {

try {// Filter QuerySession s = HibernateUtil.getSessionFactory().

getCurrentSession();Transaction tx = s.beginTransaction();System.out.println(

"*** Query item 1 for inventory quantity " +"of at least 5 ***");

s.enableFilter("byQuantity").setParameter("theQuantity", new Integer(5));

Query q = s.createQuery("FROM Inventory i WHERE i.pet.pet_id = 1");

for (Object obj : q.list()) {System.out.println(obj);

}tx.commit();

} catch (HibernateException e) {e.printStackTrace();

}catch (Exception ex) { ex.printStackTrace(); }

}

}

Page 158: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

158

Run the Test and you should see the following.

*** Query item 1 for inventory quantity of at least 5 ***18:07:54,812 DEBUG SQL:401 - select inventory0_.INVENTORY_ID asINVENTORY1_3_, inventory0_.VERSION as VERSION3_, inventory0_.locationas location3_, inventory0_.quantity as quantity3_, inventory0_.PET_IDas PET5_3_ from INVENTORY inventory0_ where inventory0_.quantity >= ?and inventory0_.PET_ID=1Hibernate: select inventory0_.INVENTORY_ID as INVENTORY1_3_,inventory0_.VERSION as VERSION3_, inventory0_.location as location3_,inventory0_.quantity as quantity3_, inventory0_.PET_ID as PET5_3_ fromINVENTORY inventory0_ where inventory0_.quantity >= ? andinventory0_.PET_ID=118:07:54,812 DEBUG IntegerType:133 - binding '5' to parameter: 118:07:54,812 DEBUG LongType:172 - returning '1' as column:INVENTORY1_3_18:07:54,828 DEBUG IntegerType:172 - returning '1' as column: VERSION3_18:07:54,828 DEBUG StringType:172 - returning 'Dallas' as column:location3_18:07:54,828 DEBUG IntegerType:172 - returning '10' as column:quantity3_18:07:54,828 DEBUG LongType:172 - returning '1' as column: PET5_3_18:07:54,828 DEBUG LongType:172 - returning '2' as column:INVENTORY1_3_18:07:54,828 DEBUG IntegerType:172 - returning '1' as column: VERSION3_18:07:54,828 DEBUG StringType:172 - returning 'Ft Worth' as column:location3_18:07:54,828 DEBUG IntegerType:172 - returning '20' as column:quantity3_18:07:54,828 DEBUG LongType:172 - returning '1' as column: PET5_3_Inventory: 1, Dallas, 10Inventory: 1, Ft Worth, 20

Page 159: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

159

Lab 21 – Criteria Query

package tests;

import java.math.BigDecimal;

import org.hibernate.Criteria;import org.hibernate.FetchMode;import org.hibernate.HibernateException;import org.hibernate.Query;import org.hibernate.Session;import org.hibernate.Transaction;import org.hibernate.criterion.Example;import org.hibernate.criterion.Restrictions;

import pets.Inventory;import pets.Pet;import utils.HibernateUtil;

public class TestCriteriaQuery {

/*** @param args*/

public static void main(String[] args) {

try {// Criteria Query

// Select all PetsSession s = HibernateUtil.getSessionFactory().

getCurrentSession();Transaction tx = s.beginTransaction();System.out.println("*** Criteria query for all Pets ***");Criteria crit = s.createCriteria(Pet.class);for (Object pet : crit.list()) {

System.out.println(pet);}

// Select Pet with pet_id=1System.out.println(

"*** Criteria query Pet for pet_id = 1 ***");crit = s.createCriteria(Pet.class).

add(Restrictions.idEq(new Long(1) ));for (Object pet : crit.list()) {

System.out.println(pet);}

Page 160: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

160

// Select Pet with license = LIC22222System.out.println(

"*** Criteria query Pet for license = " +"LIC22222 ***");

crit = s.createCriteria(Pet.class).add(Restrictions.eq("license", "LIC22222" ));

for (Object pet : crit.list()) {System.out.println(pet);

}

// Select Pets with price < 12 and id > 1System.out.println("*** Criteria and query for price < 13 and " +"pet_id > 1 ***");crit = s.createCriteria(Pet.class)

.add(Restrictions.and(Restrictions.lt("price",

new BigDecimal("13.00")),Restrictions.gt("pet_id",

new Long(1))));

for (Object pet : crit.list()) {System.out.println(pet);

}

// Select Pets with price < 13 and// pet_id > 1 using conjunctionSystem.out.println(

"*** Criteria conjunction query for price < 13 " +"and pet_id > 1 ***");

crit = s.createCriteria(Pet.class).add(Restrictions.conjunction()

.add(Restrictions.lt("price",new BigDecimal("13.00")))

.add(Restrictions.gt("pet_id",new Long(1)))

);for (Object pet : crit.list()) {

System.out.println(pet);}

Page 161: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

161

// Select inventory with quantity >= 15 and// pet_id = 1System.out.println(

"*** createAlias query on Inventory for " +"quantity >= 15 and pet.pet_id = 1 ***");

crit = s.createCriteria(Inventory.class).createAlias("pet", "i").add(Restrictions.ge("quantity",

new Integer("15"))).add(Restrictions.eq("i.pet_id",

new Long (1)));

for (Object pet : crit.list()) {System.out.println(pet);

}

// Select inventory with quantity >= 15 and "// pet_id = 1System.out.println("*** createCriteria join " +

"on Inventory for quantity >= 15 and " +"pet.pet_id = 1 ***");

crit = s.createCriteria(Inventory.class);Criteria crit2 = crit.createCriteria("pet", "i");crit.add(Restrictions.ge("quantity",

new Integer("15")));crit2.add(Restrictions.eq("i.pet_id",

new Long (1)) );for (Object pet : crit.list()) {

System.out.println(pet);}

Page 162: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

162

// Eager join on inventory recordsSystem.out.println(

"*** Eager join on Inventory Records ***");crit = s.createCriteria(Pet.class)

.setFetchMode("inventoryRecords",FetchMode.JOIN);

for (Object pet : crit.list()) {System.out.println(((Pet)pet).

getInventoryRecords().size());}

System.out.println("*** Regular query on Inventory for quantity " +">= 15 and pet.pet_id = 1 ***");

Query q = s.createQuery("SELECT inv FROM Inventory inv JOIN inv.pet i " +"WHERE quantity >= 25 AND i.pet_id = 1" );

for (Object pet : q.list()) {System.out.println(pet);

}

// Example querySystem.out.println(

"*** Example Query for Rollins ***");Pet pi = new Pet();pi.setName("Rollins");Example ex = Example.create(pi);crit = s.createCriteria(Pet.class).add(ex);for (Object pet : crit.list()) {

Pet curPet = (Pet)pet;System.out.println(curPet);

}tx.commit();

} catch (HibernateException e) {e.printStackTrace();

}catch (Exception ex) { ex.printStackTrace(); }

}

}

Page 163: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

163

Run the Test and you see the following.

*** Criteria query for all Pets ***18:34:06,546 DEBUG SQL:401 - select this_.PET_ID as PET1_0_0_,this_.VERSION as VERSION0_0_, this_.LICENSE as LICENSE0_0_, this_.NAMEas NAME0_0_, this_.DESCRIPTION as DESCRIPT5_0_0_, this_.BIRTH_DATE asBIRTH6_0_0_, this_.PRICE as PRICE0_0_, this_1_.TRICKS as TRICKS2_0_,case when this_1_.PET_ID is not null then 1 when this_.PET_ID is notnull then 0 else -1 end as clazz_0_ from PET this_ left outer join DOGthis_1_ on this_.PET_ID=this_1_.PET_IDHibernate: select this_.PET_ID as PET1_0_0_, this_.VERSION asVERSION0_0_, this_.LICENSE as LICENSE0_0_, this_.NAME as NAME0_0_,this_.DESCRIPTION as DESCRIPT5_0_0_, this_.BIRTH_DATE as BIRTH6_0_0_,this_.PRICE as PRICE0_0_, this_1_.TRICKS as TRICKS2_0_, case whenthis_1_.PET_ID is not null then 1 when this_.PET_ID is not null then 0else -1 end as clazz_0_ from PET this_ left outer join DOG this_1_ onthis_.PET_ID=this_1_.PET_ID18:34:06,546 DEBUG LongType:172 - returning '1' as column: PET1_0_0_18:34:06,546 DEBUG IntegerType:172 - returning '1' as column: clazz_0_18:34:06,546 DEBUG IntegerType:172 - returning '1' as column:VERSION0_0_18:34:06,546 DEBUG StringType:172 - returning 'LIC00000' as column:LICENSE0_0_18:34:06,546 DEBUG StringType:172 - returning 'Fido' as column:NAME0_0_18:34:06,546 DEBUG StringType:172 - returning 'Dog' as column:DESCRIPT5_0_0_18:34:06,561 DEBUG DateType:172 - returning '04 January 1992' ascolumn: BIRTH6_0_0_18:34:06,561 DEBUG BigDecimalType:172 - returning '19.95' as column:PRICE0_0_18:34:06,561 DEBUG StringType:172 - returning 'Sit, Play Dead' ascolumn: TRICKS2_0_18:34:06,561 DEBUG LongType:172 - returning '2' as column: PET1_0_0_18:34:06,561 DEBUG IntegerType:172 - returning '1' as column: clazz_0_18:34:06,561 DEBUG IntegerType:172 - returning '1' as column:VERSION0_0_18:34:06,561 DEBUG StringType:172 - returning 'LIC11111' as column:LICENSE0_0_18:34:06,561 DEBUG StringType:172 - returning 'Rex' as column: NAME0_0_18:34:06,561 DEBUG StringType:172 - returning 'Dog' as column:DESCRIPT5_0_0_18:34:06,577 DEBUG DateType:172 - returning '05 February 1994' ascolumn: BIRTH6_0_0_18:34:06,577 DEBUG BigDecimalType:172 - returning '119.95' as column:PRICE0_0_18:34:06,577 DEBUG StringType:172 - returning 'Sit, Roll Over' ascolumn: TRICKS2_0_

Page 164: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

164

18:34:06,577 DEBUG LongType:172 - returning '3' as column: PET1_0_0_18:34:06,577 DEBUG IntegerType:172 - returning '1' as column: clazz_0_18:34:06,577 DEBUG IntegerType:172 - returning '1' as column:VERSION0_0_18:34:06,577 DEBUG StringType:172 - returning 'LIC12222' as column:LICENSE0_0_18:34:06,577 DEBUG StringType:172 - returning 'Fluffy' as column:NAME0_0_18:34:06,577 DEBUG StringType:172 - returning 'Cat' as column:DESCRIPT5_0_0_18:34:06,577 DEBUG DateType:172 - returning '04 May 1998' as column:BIRTH6_0_0_18:34:06,577 DEBUG BigDecimalType:172 - returning '29.95' as column:PRICE0_0_18:34:06,577 DEBUG StringType:172 - returning 'Eat, Sleep' as column:TRICKS2_0_18:34:06,577 DEBUG LongType:172 - returning '4' as column: PET1_0_0_18:34:06,577 DEBUG IntegerType:172 - returning '1' as column: clazz_0_18:34:06,577 DEBUG IntegerType:172 - returning '1' as column:VERSION0_0_18:34:06,577 DEBUG StringType:172 - returning 'LIC33333' as column:LICENSE0_0_18:34:06,577 DEBUG StringType:172 - returning 'Goldie' as column:NAME0_0_18:34:06,577 DEBUG StringType:172 - returning 'Fish' as column:DESCRIPT5_0_0_18:34:06,577 DEBUG DateType:172 - returning '03 November 2001' ascolumn: BIRTH6_0_0_18:34:06,577 DEBUG BigDecimalType:172 - returning '39.95' as column:PRICE0_0_18:34:06,577 DEBUG StringType:172 - returning 'Eat, Swim' as column:TRICKS2_0_18:34:06,577 DEBUG LongType:172 - returning '5' as column: PET1_0_0_18:34:06,577 DEBUG IntegerType:172 - returning '1' as column: clazz_0_18:34:06,577 DEBUG IntegerType:172 - returning '1' as column:VERSION0_0_18:34:06,577 DEBUG StringType:172 - returning 'LIC44444' as column:LICENSE0_0_18:34:06,577 DEBUG StringType:172 - returning 'Slinky' as column:NAME0_0_18:34:06,577 DEBUG StringType:172 - returning 'Snake' as column:DESCRIPT5_0_0_18:34:06,577 DEBUG DateType:172 - returning '10 December 2002' ascolumn: BIRTH6_0_0_18:34:06,577 DEBUG BigDecimalType:172 - returning '49.95' as column:PRICE0_0_18:34:06,577 DEBUG StringType:172 - returning 'Sleep, Eat' as column:TRICKS2_0_

Page 165: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

165

18:34:06,577 DEBUG LongType:172 - returning '6' as column: PET1_0_0_18:34:06,577 DEBUG IntegerType:172 - returning '0' as column: clazz_0_18:34:06,577 DEBUG IntegerType:172 - returning '1' as column:VERSION0_0_18:34:06,577 DEBUG StringType:172 - returning 'LIC55555' as column:LICENSE0_0_18:34:06,577 DEBUG StringType:172 - returning 'Spot' as column:NAME0_0_18:34:06,577 DEBUG StringType:172 - returning 'Dog' as column:DESCRIPT5_0_0_18:34:06,577 DEBUG DateType:172 - returning '15 June 2004' as column:BIRTH6_0_0_18:34:06,577 DEBUG BigDecimalType:172 - returning '40.95' as column:PRICE0_0_18:34:06,577 DEBUG LongType:172 - returning '7' as column: PET1_0_0_18:34:06,592 DEBUG IntegerType:172 - returning '0' as column: clazz_0_18:34:06,592 DEBUG IntegerType:172 - returning '1' as column:VERSION0_0_18:34:06,592 DEBUG StringType:172 - returning 'LIC66666' as column:LICENSE0_0_18:34:06,592 DEBUG StringType:172 - returning 'Inky' as column:NAME0_0_18:34:06,592 DEBUG StringType:172 - returning 'Cat' as column:DESCRIPT5_0_0_18:34:06,592 DEBUG DateType:172 - returning '24 January 2006' ascolumn: BIRTH6_0_0_18:34:06,592 DEBUG BigDecimalType:172 - returning '110.95' as column:PRICE0_0_18:34:06,592 DEBUG LongType:172 - returning '8' as column: PET1_0_0_18:34:06,592 DEBUG IntegerType:172 - returning '0' as column: clazz_0_18:34:06,592 DEBUG IntegerType:172 - returning '1' as column:VERSION0_0_18:34:06,592 DEBUG StringType:172 - returning 'LIC77777' as column:LICENSE0_0_18:34:06,592 DEBUG StringType:172 - returning 'Bubbles' as column:NAME0_0_18:34:06,592 DEBUG StringType:172 - returning 'Fish' as column:DESCRIPT5_0_0_18:34:06,592 DEBUG DateType:172 - returning '14 February 1992' ascolumn: BIRTH6_0_0_18:34:06,592 DEBUG BigDecimalType:172 - returning '16.95' as column:PRICE0_0_18:34:06,592 DEBUG LongType:172 - returning '9' as column: PET1_0_0_18:34:06,592 DEBUG IntegerType:172 - returning '0' as column: clazz_0_18:34:06,592 DEBUG IntegerType:172 - returning '1' as column:VERSION0_0_18:34:06,592 DEBUG StringType:172 - returning 'LIC88888' as column:LICENSE0_0_18:34:06,592 DEBUG StringType:172 - returning 'Arson' as column:NAME0_0_

Page 166: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

166

18:34:06,592 DEBUG StringType:172 - returning 'Dog' as column:DESCRIPT5_0_0_18:34:06,592 DEBUG DateType:172 - returning '14 March 1991' as column:BIRTH6_0_0_18:34:06,592 DEBUG BigDecimalType:172 - returning '10.95' as column:PRICE0_0_18:34:06,592 DEBUG LongType:172 - returning '10' as column: PET1_0_0_18:34:06,592 DEBUG IntegerType:172 - returning '0' as column: clazz_0_18:34:06,592 DEBUG IntegerType:172 - returning '1' as column:VERSION0_0_18:34:06,592 DEBUG StringType:172 - returning 'LIC99999' as column:LICENSE0_0_18:34:06,592 DEBUG StringType:172 - returning 'Rollins' as column:NAME0_0_18:34:06,592 DEBUG StringType:172 - returning 'Dog' as column:DESCRIPT5_0_0_18:34:06,592 DEBUG DateType:172 - returning '24 April 1992' as column:BIRTH6_0_0_18:34:06,592 DEBUG BigDecimalType:172 - returning '120.95' as column:PRICE0_0_pets.Dog@1, Pet_ID: 1, Name: Fido, Description: Dog, Price: 19.95, Dateof Birth: 1992-01-04Tricks: Sit, Play Deadpets.Dog@2, Pet_ID: 2, Name: Rex, Description: Dog, Price: 119.95, Dateof Birth: 1994-02-05Tricks: Sit, Roll Overpets.Dog@3, Pet_ID: 3, Name: Fluffy, Description: Cat, Price: 29.95,Date of Birth: 1998-05-04Tricks: Eat, Sleeppets.Dog@4, Pet_ID: 4, Name: Goldie, Description: Fish, Price: 39.95,Date of Birth: 2001-11-03Tricks: Eat, Swimpets.Dog@5, Pet_ID: 5, Name: Slinky, Description: Snake, Price: 49.95,Date of Birth: 2002-12-10Tricks: Sleep, Eatpets.Pet@6, Pet_ID: 6, Name: Spot, Description: Dog, Price: 40.95, Dateof Birth: 2004-06-15pets.Pet@7, Pet_ID: 7, Name: Inky, Description: Cat, Price: 110.95,Date of Birth: 2006-01-24pets.Pet@8, Pet_ID: 8, Name: Bubbles, Description: Fish, Price: 16.95,Date of Birth: 1992-02-14pets.Pet@9, Pet_ID: 9, Name: Arson, Description: Dog, Price: 10.95,Date of Birth: 1991-03-14pets.Pet@a, Pet_ID: 10, Name: Rollins, Description: Dog, Price: 120.95,Date of Birth: 1992-04-24

Page 167: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

167

*** Criteria query Pet for pet_id = 1 ***18:34:06,639 DEBUG SQL:401 - select this_.PET_ID as PET1_0_0_,this_.VERSION as VERSION0_0_, this_.LICENSE as LICENSE0_0_, this_.NAMEas NAME0_0_, this_.DESCRIPTION as DESCRIPT5_0_0_, this_.BIRTH_DATE asBIRTH6_0_0_, this_.PRICE as PRICE0_0_, this_1_.TRICKS as TRICKS2_0_,case when this_1_.PET_ID is not null then 1 when this_.PET_ID is notnull then 0 else -1 end as clazz_0_ from PET this_ left outer join DOGthis_1_ on this_.PET_ID=this_1_.PET_ID where this_.PET_ID = ?Hibernate: select this_.PET_ID as PET1_0_0_, this_.VERSION asVERSION0_0_, this_.LICENSE as LICENSE0_0_, this_.NAME as NAME0_0_,this_.DESCRIPTION as DESCRIPT5_0_0_, this_.BIRTH_DATE as BIRTH6_0_0_,this_.PRICE as PRICE0_0_, this_1_.TRICKS as TRICKS2_0_, case whenthis_1_.PET_ID is not null then 1 when this_.PET_ID is not null then 0else -1 end as clazz_0_ from PET this_ left outer join DOG this_1_ onthis_.PET_ID=this_1_.PET_ID where this_.PET_ID = ?18:34:06,639 DEBUG LongType:133 - binding '1' to parameter: 118:34:06,639 DEBUG LongType:172 - returning '1' as column: PET1_0_0_pets.Dog@1, Pet_ID: 1, Name: Fido, Description: Dog, Price: 19.95, Dateof Birth: 1992-01-04Tricks: Sit, Play Dead*** Criteria query Pet for license = LIC22222 ***18:34:06,639 DEBUG SQL:401 - select this_.PET_ID as PET1_0_0_,this_.VERSION as VERSION0_0_, this_.LICENSE as LICENSE0_0_, this_.NAMEas NAME0_0_, this_.DESCRIPTION as DESCRIPT5_0_0_, this_.BIRTH_DATE asBIRTH6_0_0_, this_.PRICE as PRICE0_0_, this_1_.TRICKS as TRICKS2_0_,case when this_1_.PET_ID is not null then 1 when this_.PET_ID is notnull then 0 else -1 end as clazz_0_ from PET this_ left outer join DOGthis_1_ on this_.PET_ID=this_1_.PET_ID where this_.LICENSE=?Hibernate: select this_.PET_ID as PET1_0_0_, this_.VERSION asVERSION0_0_, this_.LICENSE as LICENSE0_0_, this_.NAME as NAME0_0_,this_.DESCRIPTION as DESCRIPT5_0_0_, this_.BIRTH_DATE as BIRTH6_0_0_,this_.PRICE as PRICE0_0_, this_1_.TRICKS as TRICKS2_0_, case whenthis_1_.PET_ID is not null then 1 when this_.PET_ID is not null then 0else -1 end as clazz_0_ from PET this_ left outer join DOG this_1_ onthis_.PET_ID=this_1_.PET_ID where this_.LICENSE=?18:34:06,639 DEBUG StringType:133 - binding 'LIC22222' to parameter: 1*** Criteria and query for price < 13 and pet_id > 1 ***18:34:06,655 DEBUG SQL:401 - select this_.PET_ID as PET1_0_0_,this_.VERSION as VERSION0_0_, this_.LICENSE as LICENSE0_0_, this_.NAMEas NAME0_0_, this_.DESCRIPTION as DESCRIPT5_0_0_, this_.BIRTH_DATE asBIRTH6_0_0_, this_.PRICE as PRICE0_0_, this_1_.TRICKS as TRICKS2_0_,case when this_1_.PET_ID is not null then 1 when this_.PET_ID is notnull then 0 else -1 end as clazz_0_ from PET this_ left outer join DOGthis_1_ on this_.PET_ID=this_1_.PET_ID where (this_.PRICE<? andthis_.PET_ID>?)

Page 168: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

168

Hibernate: select this_.PET_ID as PET1_0_0_, this_.VERSION asVERSION0_0_, this_.LICENSE as LICENSE0_0_, this_.NAME as NAME0_0_,this_.DESCRIPTION as DESCRIPT5_0_0_, this_.BIRTH_DATE as BIRTH6_0_0_,this_.PRICE as PRICE0_0_, this_1_.TRICKS as TRICKS2_0_, case whenthis_1_.PET_ID is not null then 1 when this_.PET_ID is not null then 0else -1 end as clazz_0_ from PET this_ left outer join DOG this_1_ onthis_.PET_ID=this_1_.PET_ID where (this_.PRICE<? and this_.PET_ID>?)18:34:06,655 DEBUG BigDecimalType:133 - binding '13.00' to parameter: 118:34:06,655 DEBUG LongType:133 - binding '1' to parameter: 218:34:06,655 DEBUG LongType:172 - returning '9' as column: PET1_0_0_pets.Pet@9, Pet_ID: 9, Name: Arson, Description: Dog, Price: 10.95,Date of Birth: 1991-03-14*** Criteria conjunction query for price < 13 and pet_id > 1 ***18:34:06,671 DEBUG SQL:401 - select this_.PET_ID as PET1_0_0_,this_.VERSION as VERSION0_0_, this_.LICENSE as LICENSE0_0_, this_.NAMEas NAME0_0_, this_.DESCRIPTION as DESCRIPT5_0_0_, this_.BIRTH_DATE asBIRTH6_0_0_, this_.PRICE as PRICE0_0_, this_1_.TRICKS as TRICKS2_0_,case when this_1_.PET_ID is not null then 1 when this_.PET_ID is notnull then 0 else -1 end as clazz_0_ from PET this_ left outer join DOGthis_1_ on this_.PET_ID=this_1_.PET_ID where (this_.PRICE<? andthis_.PET_ID>?)Hibernate: select this_.PET_ID as PET1_0_0_, this_.VERSION asVERSION0_0_, this_.LICENSE as LICENSE0_0_, this_.NAME as NAME0_0_,this_.DESCRIPTION as DESCRIPT5_0_0_, this_.BIRTH_DATE as BIRTH6_0_0_,this_.PRICE as PRICE0_0_, this_1_.TRICKS as TRICKS2_0_, case whenthis_1_.PET_ID is not null then 1 when this_.PET_ID is not null then 0else -1 end as clazz_0_ from PET this_ left outer join DOG this_1_ onthis_.PET_ID=this_1_.PET_ID where (this_.PRICE<? and this_.PET_ID>?)18:34:06,671 DEBUG BigDecimalType:133 - binding '13.00' to parameter: 118:34:06,671 DEBUG LongType:133 - binding '1' to parameter: 218:34:06,671 DEBUG LongType:172 - returning '9' as column: PET1_0_0_pets.Pet@9, Pet_ID: 9, Name: Arson, Description: Dog, Price: 10.95,Date of Birth: 1991-03-14

Page 169: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

169

*** createAlias query on Inventory for quantity >= 15 and pet.pet_id =1 ***18:34:06,686 DEBUG SQL:401 - select this_.INVENTORY_ID asINVENTORY1_3_1_, this_.VERSION as VERSION3_1_, this_.location aslocation3_1_, this_.quantity as quantity3_1_, this_.PET_ID asPET5_3_1_, i1_.PET_ID as PET1_0_0_, i1_.VERSION as VERSION0_0_,i1_.LICENSE as LICENSE0_0_, i1_.NAME as NAME0_0_, i1_.DESCRIPTION asDESCRIPT5_0_0_, i1_.BIRTH_DATE as BIRTH6_0_0_, i1_.PRICE as PRICE0_0_,i1_1_.TRICKS as TRICKS2_0_, case when i1_1_.PET_ID is not null then 1when i1_.PET_ID is not null then 0 else -1 end as clazz_0_ fromINVENTORY this_ inner join PET i1_ on this_.PET_ID=i1_.PET_ID leftouter join DOG i1_1_ on i1_.PET_ID=i1_1_.PET_ID where this_.quantity>=?and i1_.PET_ID=?Hibernate: select this_.INVENTORY_ID as INVENTORY1_3_1_, this_.VERSIONas VERSION3_1_, this_.location as location3_1_, this_.quantity asquantity3_1_, this_.PET_ID as PET5_3_1_, i1_.PET_ID as PET1_0_0_,i1_.VERSION as VERSION0_0_, i1_.LICENSE as LICENSE0_0_, i1_.NAME asNAME0_0_, i1_.DESCRIPTION as DESCRIPT5_0_0_, i1_.BIRTH_DATE asBIRTH6_0_0_, i1_.PRICE as PRICE0_0_, i1_1_.TRICKS as TRICKS2_0_, casewhen i1_1_.PET_ID is not null then 1 when i1_.PET_ID is not null then 0else -1 end as clazz_0_ from INVENTORY this_ inner join PET i1_ onthis_.PET_ID=i1_.PET_ID left outer join DOG i1_1_ oni1_.PET_ID=i1_1_.PET_ID where this_.quantity>=? and i1_.PET_ID=?18:34:06,686 DEBUG IntegerType:133 - binding '15' to parameter: 118:34:06,686 DEBUG LongType:133 - binding '1' to parameter: 218:34:06,686 DEBUG LongType:172 - returning '1' as column: PET1_0_0_18:34:06,686 DEBUG LongType:172 - returning '2' as column:INVENTORY1_3_1_18:34:06,686 DEBUG IntegerType:172 - returning '1' as column:VERSION3_1_18:34:06,686 DEBUG StringType:172 - returning 'Ft Worth' as column:location3_1_18:34:06,686 DEBUG IntegerType:172 - returning '20' as column:quantity3_1_18:34:06,686 DEBUG LongType:172 - returning '1' as column: PET5_3_1_Inventory: 1, Ft Worth, 20

Page 170: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

170

*** createCriteria join on Inventory for quantity >= 15 and pet.pet_id= 1 ***18:34:06,686 DEBUG SQL:401 - select this_.INVENTORY_ID asINVENTORY1_3_1_, this_.VERSION as VERSION3_1_, this_.location aslocation3_1_, this_.quantity as quantity3_1_, this_.PET_ID asPET5_3_1_, i1_.PET_ID as PET1_0_0_, i1_.VERSION as VERSION0_0_,i1_.LICENSE as LICENSE0_0_, i1_.NAME as NAME0_0_, i1_.DESCRIPTION asDESCRIPT5_0_0_, i1_.BIRTH_DATE as BIRTH6_0_0_, i1_.PRICE as PRICE0_0_,i1_1_.TRICKS as TRICKS2_0_, case when i1_1_.PET_ID is not null then 1when i1_.PET_ID is not null then 0 else -1 end as clazz_0_ fromINVENTORY this_ inner join PET i1_ on this_.PET_ID=i1_.PET_ID leftouter join DOG i1_1_ on i1_.PET_ID=i1_1_.PET_ID where this_.quantity>=?and i1_.PET_ID=?Hibernate: select this_.INVENTORY_ID as INVENTORY1_3_1_, this_.VERSIONas VERSION3_1_, this_.location as location3_1_, this_.quantity asquantity3_1_, this_.PET_ID as PET5_3_1_, i1_.PET_ID as PET1_0_0_,i1_.VERSION as VERSION0_0_, i1_.LICENSE as LICENSE0_0_, i1_.NAME asNAME0_0_, i1_.DESCRIPTION as DESCRIPT5_0_0_, i1_.BIRTH_DATE asBIRTH6_0_0_, i1_.PRICE as PRICE0_0_, i1_1_.TRICKS as TRICKS2_0_, casewhen i1_1_.PET_ID is not null then 1 when i1_.PET_ID is not null then 0else -1 end as clazz_0_ from INVENTORY this_ inner join PET i1_ onthis_.PET_ID=i1_.PET_ID left outer join DOG i1_1_ oni1_.PET_ID=i1_1_.PET_ID where this_.quantity>=? and i1_.PET_ID=?18:34:06,702 DEBUG IntegerType:133 - binding '15' to parameter: 118:34:06,702 DEBUG LongType:133 - binding '1' to parameter: 218:34:06,702 DEBUG LongType:172 - returning '1' as column: PET1_0_0_18:34:06,702 DEBUG LongType:172 - returning '2' as column:INVENTORY1_3_1_Inventory: 1, Ft Worth, 20

Page 171: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

171

*** Eager join on Inventory Records ***18:34:06,702 DEBUG SQL:401 - select this_.PET_ID as PET1_0_1_,this_.VERSION as VERSION0_1_, this_.LICENSE as LICENSE0_1_, this_.NAMEas NAME0_1_, this_.DESCRIPTION as DESCRIPT5_0_1_, this_.BIRTH_DATE asBIRTH6_0_1_, this_.PRICE as PRICE0_1_, this_1_.TRICKS as TRICKS2_1_,case when this_1_.PET_ID is not null then 1 when this_.PET_ID is notnull then 0 else -1 end as clazz_1_, inventoryr2_.PET_ID as PET5_3_,inventoryr2_.INVENTORY_ID as INVENTORY1_3_, inventoryr2_.INVENTORY_IDas INVENTORY1_3_0_, inventoryr2_.VERSION as VERSION3_0_,inventoryr2_.location as location3_0_, inventoryr2_.quantity asquantity3_0_, inventoryr2_.PET_ID as PET5_3_0_ from PET this_ leftouter join DOG this_1_ on this_.PET_ID=this_1_.PET_ID left outer joinINVENTORY inventoryr2_ on this_.PET_ID=inventoryr2_.PET_IDHibernate: select this_.PET_ID as PET1_0_1_, this_.VERSION asVERSION0_1_, this_.LICENSE as LICENSE0_1_, this_.NAME as NAME0_1_,this_.DESCRIPTION as DESCRIPT5_0_1_, this_.BIRTH_DATE as BIRTH6_0_1_,this_.PRICE as PRICE0_1_, this_1_.TRICKS as TRICKS2_1_, case whenthis_1_.PET_ID is not null then 1 when this_.PET_ID is not null then 0else -1 end as clazz_1_, inventoryr2_.PET_ID as PET5_3_,inventoryr2_.INVENTORY_ID as INVENTORY1_3_, inventoryr2_.INVENTORY_IDas INVENTORY1_3_0_, inventoryr2_.VERSION as VERSION3_0_,inventoryr2_.location as location3_0_, inventoryr2_.quantity asquantity3_0_, inventoryr2_.PET_ID as PET5_3_0_ from PET this_ leftouter join DOG this_1_ on this_.PET_ID=this_1_.PET_ID left outer joinINVENTORY inventoryr2_ on this_.PET_ID=inventoryr2_.PET_ID18:34:06,702 DEBUG LongType:172 - returning '1' as column:INVENTORY1_3_0_18:34:06,702 DEBUG LongType:172 - returning '1' as column: PET1_0_1_18:34:06,702 DEBUG IntegerType:172 - returning '1' as column:VERSION3_0_18:34:06,717 DEBUG StringType:172 - returning 'Dallas' as column:location3_0_18:34:06,717 DEBUG IntegerType:172 - returning '10' as column:quantity3_0_18:34:06,717 DEBUG LongType:172 - returning '1' as column: PET5_3_0_18:34:06,717 DEBUG LongType:172 - returning '1' as column: PET5_3_18:34:06,717 DEBUG LongType:172 - returning '1' as column:INVENTORY1_3_18:34:06,717 DEBUG LongType:172 - returning '2' as column:INVENTORY1_3_0_18:34:06,717 DEBUG LongType:172 - returning '1' as column: PET1_0_1_18:34:06,717 DEBUG LongType:172 - returning '1' as column: PET5_3_18:34:06,717 DEBUG LongType:172 - returning '2' as column:INVENTORY1_3_18:34:06,717 DEBUG LongType:172 - returning '3' as column:INVENTORY1_3_0_

Page 172: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

172

18:34:06,717 DEBUG LongType:172 - returning '2' as column: PET1_0_1_18:34:06,717 DEBUG IntegerType:172 - returning '1' as column:VERSION3_0_18:34:06,717 DEBUG StringType:172 - returning 'Dallas' as column:location3_0_18:34:06,717 DEBUG IntegerType:172 - returning '15' as column:quantity3_0_18:34:06,717 DEBUG LongType:172 - returning '2' as column: PET5_3_0_18:34:06,717 DEBUG LongType:172 - returning '2' as column: PET5_3_18:34:06,717 DEBUG LongType:172 - returning '3' as column:INVENTORY1_3_18:34:06,717 DEBUG LongType:172 - returning '4' as column:INVENTORY1_3_0_18:34:06,717 DEBUG LongType:172 - returning '3' as column: PET1_0_1_18:34:06,717 DEBUG IntegerType:172 - returning '1' as column:VERSION3_0_18:34:06,733 DEBUG StringType:172 - returning 'Dallas' as column:location3_0_18:34:06,733 DEBUG IntegerType:172 - returning '5' as column:quantity3_0_18:34:06,733 DEBUG LongType:172 - returning '3' as column: PET5_3_0_18:34:06,733 DEBUG LongType:172 - returning '3' as column: PET5_3_18:34:06,733 DEBUG LongType:172 - returning '4' as column:INVENTORY1_3_18:34:06,733 DEBUG LongType:172 - returning '5' as column:INVENTORY1_3_0_18:34:06,733 DEBUG LongType:172 - returning '4' as column: PET1_0_1_18:34:06,733 DEBUG IntegerType:172 - returning '1' as column:VERSION3_0_18:34:06,733 DEBUG StringType:172 - returning 'Dallas' as column:location3_0_18:34:06,733 DEBUG IntegerType:172 - returning '8' as column:quantity3_0_18:34:06,733 DEBUG LongType:172 - returning '4' as column: PET5_3_0_18:34:06,733 DEBUG LongType:172 - returning '4' as column: PET5_3_18:34:06,733 DEBUG LongType:172 - returning '5' as column:INVENTORY1_3_18:34:06,733 DEBUG LongType:172 - returning '6' as column:INVENTORY1_3_0_18:34:06,733 DEBUG LongType:172 - returning '5' as column: PET1_0_1_18:34:06,733 DEBUG IntegerType:172 - returning '1' as column:VERSION3_0_18:34:06,733 DEBUG StringType:172 - returning 'Dallas' as column:location3_0_18:34:06,733 DEBUG IntegerType:172 - returning '18' as column:quantity3_0_18:34:06,733 DEBUG LongType:172 - returning '5' as column: PET5_3_0_18:34:06,733 DEBUG LongType:172 - returning '5' as column: PET5_3_18:34:06,733 DEBUG LongType:172 - returning '6' as column:INVENTORY1_3_

Page 173: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

173

18:34:06,733 DEBUG LongType:172 - returning '7' as column:INVENTORY1_3_0_18:34:06,733 DEBUG LongType:172 - returning '6' as column: PET1_0_1_18:34:06,733 DEBUG IntegerType:172 - returning '1' as column:VERSION3_0_18:34:06,733 DEBUG StringType:172 - returning 'Dallas' as column:location3_0_18:34:06,733 DEBUG IntegerType:172 - returning '3' as column:quantity3_0_18:34:06,733 DEBUG LongType:172 - returning '6' as column: PET5_3_0_18:34:06,733 DEBUG LongType:172 - returning '6' as column: PET5_3_18:34:06,733 DEBUG LongType:172 - returning '7' as column:INVENTORY1_3_18:34:06,733 DEBUG LongType:172 - returning '8' as column:INVENTORY1_3_0_18:34:06,733 DEBUG LongType:172 - returning '7' as column: PET1_0_1_18:34:06,733 DEBUG IntegerType:172 - returning '1' as column:VERSION3_0_18:34:06,733 DEBUG StringType:172 - returning 'Dallas' as column:location3_0_18:34:06,733 DEBUG IntegerType:172 - returning '21' as column:quantity3_0_18:34:06,733 DEBUG LongType:172 - returning '7' as column: PET5_3_0_18:34:06,733 DEBUG LongType:172 - returning '7' as column: PET5_3_18:34:06,733 DEBUG LongType:172 - returning '8' as column:INVENTORY1_3_18:34:06,733 DEBUG LongType:172 - returning '9' as column:INVENTORY1_3_0_18:34:06,733 DEBUG LongType:172 - returning '8' as column: PET1_0_1_18:34:06,733 DEBUG IntegerType:172 - returning '1' as column:VERSION3_0_18:34:06,733 DEBUG StringType:172 - returning 'Dallas' as column:location3_0_18:34:06,733 DEBUG IntegerType:172 - returning '4' as column:quantity3_0_18:34:06,733 DEBUG LongType:172 - returning '8' as column: PET5_3_0_18:34:06,733 DEBUG LongType:172 - returning '8' as column: PET5_3_18:34:06,733 DEBUG LongType:172 - returning '9' as column:INVENTORY1_3_18:34:06,733 DEBUG LongType:172 - returning '10' as column:INVENTORY1_3_0_18:34:06,733 DEBUG LongType:172 - returning '9' as column: PET1_0_1_18:34:06,733 DEBUG IntegerType:172 - returning '1' as column:VERSION3_0_

Page 174: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

174

18:34:06,733 DEBUG StringType:172 - returning 'Dallas' as column:location3_0_18:34:06,733 DEBUG IntegerType:172 - returning '2' as column:quantity3_0_18:34:06,733 DEBUG LongType:172 - returning '9' as column: PET5_3_0_18:34:06,733 DEBUG LongType:172 - returning '9' as column: PET5_3_18:34:06,733 DEBUG LongType:172 - returning '10' as column:INVENTORY1_3_18:34:06,733 DEBUG LongType:172 - returning '11' as column:INVENTORY1_3_0_18:34:06,733 DEBUG LongType:172 - returning '10' as column: PET1_0_1_18:34:06,733 DEBUG IntegerType:172 - returning '1' as column:VERSION3_0_18:34:06,733 DEBUG StringType:172 - returning 'Dallas' as column:location3_0_18:34:06,733 DEBUG IntegerType:172 - returning '1' as column:quantity3_0_18:34:06,749 DEBUG LongType:172 - returning '10' as column: PET5_3_0_18:34:06,749 DEBUG LongType:172 - returning '10' as column: PET5_3_18:34:06,749 DEBUG LongType:172 - returning '11' as column:INVENTORY1_3_22111111111

Page 175: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

175

*** Regular query on Inventory for quantity >= 15 and pet.pet_id = 1***18:34:06,764 DEBUG SQL:401 - select inventory0_.INVENTORY_ID asINVENTORY1_3_, inventory0_.VERSION as VERSION3_, inventory0_.locationas location3_, inventory0_.quantity as quantity3_, inventory0_.PET_IDas PET5_3_ from INVENTORY inventory0_ inner join PET pet1_ oninventory0_.PET_ID=pet1_.PET_ID where quantity>=25 and pet1_.PET_ID=1Hibernate: select inventory0_.INVENTORY_ID as INVENTORY1_3_,inventory0_.VERSION as VERSION3_, inventory0_.location as location3_,inventory0_.quantity as quantity3_, inventory0_.PET_ID as PET5_3_ fromINVENTORY inventory0_ inner join PET pet1_ oninventory0_.PET_ID=pet1_.PET_ID where quantity>=25 and pet1_.PET_ID=1*** Example Query for Rollins ***18:34:06,780 DEBUG SQL:401 - select this_.PET_ID as PET1_0_0_,this_.VERSION as VERSION0_0_, this_.LICENSE as LICENSE0_0_, this_.NAMEas NAME0_0_, this_.DESCRIPTION as DESCRIPT5_0_0_, this_.BIRTH_DATE asBIRTH6_0_0_, this_.PRICE as PRICE0_0_, this_1_.TRICKS as TRICKS2_0_,case when this_1_.PET_ID is not null then 1 when this_.PET_ID is notnull then 0 else -1 end as clazz_0_ from PET this_ left outer join DOGthis_1_ on this_.PET_ID=this_1_.PET_ID where (this_.NAME=?)Hibernate: select this_.PET_ID as PET1_0_0_, this_.VERSION asVERSION0_0_, this_.LICENSE as LICENSE0_0_, this_.NAME as NAME0_0_,this_.DESCRIPTION as DESCRIPT5_0_0_, this_.BIRTH_DATE as BIRTH6_0_0_,this_.PRICE as PRICE0_0_, this_1_.TRICKS as TRICKS2_0_, case whenthis_1_.PET_ID is not null then 1 when this_.PET_ID is not null then 0else -1 end as clazz_0_ from PET this_ left outer join DOG this_1_ onthis_.PET_ID=this_1_.PET_ID where (this_.NAME=?)18:34:06,780 DEBUG StringType:133 - binding 'Rollins' to parameter: 118:34:06,780 DEBUG LongType:172 - returning '10' as column: PET1_0_0_pets.Pet@a, Pet_ID: 10, Name: Rollins, Description: Dog, Price: 120.95,Date of Birth: 1992-04-24

Page 176: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

176

Lab 22 – JPA

Download and Install from www.hibernate.org:

hibernate-annotations-3.2.1.GA.zip

hibernate-entitymanager-3.2.1.GA.zip

Add the following 2 JAR files to the User Library from c:\hibernate-3.2\lib.

Page 177: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

177

Add the following JAR from C:\hibernate-annotations-3.2.1.GA

Page 178: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

178

Add the following JAR from C:\hibernate-annotations-3.2.1.GA\lib.

Page 179: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

179

Add the following JAR from C:\hibernate-entitymanager-3.2.1.GA

Page 180: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

180

Create a new folder named META-INF in the src folder.

Page 181: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

181

Create a new XML file in the META-INF folder called persistence.xml.

Page 182: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

182

Add the following.

<?xml version="1.0" encoding="UTF-8"?>

<persistence xmlns="http://java.sun.com/xml/ns/persistence"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://java.sun.com/xml/ns/persistence

http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"version="1.0">

<persistence-unit name="pets" transaction-type="RESOURCE_LOCAL">

<properties><property name="hibernate.connection.username"

value="user"/><property name="hibernate.connection.password"

value="password"/><property name="hibernate.connection.url"

value="jdbc:derby://localhost:1527/PetDB"/><property name="hibernate.connection.driver_class"

value="org.apache.derby.jdbc.ClientDriver"/><property name="hibernate.dialect"

value="org.hibernate.dialect.DerbyDialect"/><property name="hibernate.connection.pool_size"

value="1"/>

<!-- Use Thread local contextual sessions --><property name="hibernate.current_session_context_class"

value="thread"/>

<!-- Disable the second-level cache --><property name="hibernate.cache.provider_class"

value="org.hibernate.cache.NoCacheProvider"/>

</properties>

</persistence-unit>

</persistence>

Page 183: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

183

Add the following Annotations to the class Pet.

package pets;

import java.io.Serializable;import java.math.BigDecimal;import java.sql.Date;import java.util.HashSet;import java.util.Set;

import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;import javax.persistence.Table;import javax.persistence.Transient;

@Entity@Table(name="Pet")public class Pet implements Serializable {

@Id@GeneratedValue(strategy=GenerationType.IDENTITY)@Column(name="PET_ID")private Long pet_id;

private String license;private String name;private String description;private Date birth_date;private BigDecimal price;

private Set nicknames = new HashSet();

@Transientprivate Set inventoryRecords = new HashSet();

@Transientprivate Integer version;

Page 184: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

184

public Set getNicknames() {return nicknames;

}

public void setNicknames(Set nicknames) {this.nicknames = nicknames;

}

public Integer getVersion() {return version;

}

public void setVersion(Integer version) {this.version = version;

}

public Long getPet_id() {return pet_id;

}

public void setPet_id(Long pet_id) {this.pet_id = pet_id;

}

public String getLicense() {return license;

}

public void setLicense(String license) {this.license = license;

}

public String getName() {return name;

}

public void setName(String name) {this.name = name;

}

public String getDescription() {return description;

}

public void setDescription(String description) {this.description = description;

}

Page 185: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

185

public Date getBirth_date() {return birth_date;

}

public void setBirth_date(Date birth_date) {this.birth_date = birth_date;

}

public BigDecimal getPrice() {return price;

}

public void setPrice(BigDecimal price) {this.price = price;

}

public Pet() {super();

}

public Pet(Long pet_id, String license,String name, String description,Date birth_date, BigDecimal price) {

this();this.pet_id = pet_id;this.license = license;this.name = name;this.description = description;this.birth_date = birth_date;this.price = price;

}

public boolean equals(Object that) {if (this == that) {

return true;} else if (!(that instanceof Pet)) {

return false;} else {

return ((Pet) that).getPet_id().equals(this.getPet_id());

}}

Page 186: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

186

public int hashCode() {return getPet_id().hashCode();

}

public String toString() {return super.toString() + ", " +

"Pet_ID: " + getPet_id() + ", " +"Name: " + getName() + ", " +"Description: " + getDescription() + ", " +"Price: " + getPrice() + ", " +"Date of Birth: " + getBirth_date();

}

public Set getInventoryRecords() {return inventoryRecords;

}

public void setInventoryRecords(Set inventoryRecords) {this.inventoryRecords = inventoryRecords;

}

public void addInventoryRecord(String location, int quantity) {Inventory inv = new Inventory(location, quantity);inv.setPet(this);getInventoryRecords().add(inv);

}

}

Page 187: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

187

Create a new class named TestJPA and add the following.

package tests;

import javax.persistence.EntityManager;import javax.persistence.EntityTransaction;import javax.persistence.Persistence;import pets.Pet;

public class TestJPA {

/*** @param args*/

public static void main(String[] args) {EntityManager em = Persistence.

createEntityManagerFactory("pets").createEntityManager();

EntityTransaction tx = null;try {

tx = em.getTransaction();tx.begin();Pet pet = em.find(Pet.class, new Long(1));System.out.println(pet);tx.commit();

}catch (Exception ex) { ex.printStackTrace(); }finally { em.close(); }

}

}

Page 188: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

188

Run the Test and you should see the following.

pets.Dog@1, Pet_ID: 1, Name: Fido, Description: Dog, Price: 19.95, Dateof Birth: 1992-01-04Tricks: Sit, Play Dead

Page 189: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

189

Lab 23 – Second Level Cache

Add the following JAR file to the User Library.

Page 190: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

190

Update hibernate.cfg.xml to use Second-Level Caching.

<!-- Configure Cache --><property name="hibernate.cache.provider_class">

org.hibernate.cache.EhCacheProvider</property>

Page 191: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

191

Create a new XML file in the src directory named ehcache.xml.

Page 192: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

192

Add the following.

<?xml version="1.0" encoding="UTF-8"?>

<ehcache><diskStore path="java.io.tmp"/>

<defaultCachemaxElementsInMemory="10"eternal="false"timeToIdleSeconds="120"timeToLiveSeconds="120"overflowToDisk="true"/>

<cache name="pets.LocationEvent"maxElementsInMemory="20"eternal="false"timeToIdleSeconds="120"timeToLiveSeconds="180"overflowToDisk="true"/>

</ehcache>

Page 193: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

193

Update Location.hbm.xml with the following.

<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC

"-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>

<class name="pets.Inventory" table="INVENTORY" >

<cache usage="read-write"/>

<id name="inventory_id" column="INVENTORY_ID"access="field"><generator class="identity"/>

</id>

<version column="VERSION" name="version"type="integer" access="field"unsaved-value="negative"/>

<property name="location"/><property name="quantity"/>

<many-to-one name="pet" column="PET_ID"class="pets.Pet"/>

<filter name="byQuantity" condition="quantity >= :theQuantity"/>

</class>

<filter-def name="byQuantity"><filter-param name="theQuantity" type="integer"/>

</filter-def>

</hibernate-mapping>

Page 194: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

194

Create a new class named TestCache and enter the following.

package tests;

import org.hibernate.HibernateException;import org.hibernate.Session;

import pets.Pet;import utils.HibernateUtil;

public class TestCache {

/*** @param args*/

public static void main(String[] args) {

Session s;

try {s = HibernateUtil.getSessionFactory().

getCurrentSession();s.beginTransaction();

System.out.println("*** Session connect status: " + s.isConnected());

Pet pet = (Pet)s.get(Pet.class, new Long(1));for (Object cur : pet.getInventoryRecords()) {

System.out.println(cur);}

s.getTransaction().commit();System.out.println(

"After commit session open state = " + s.isOpen());

} catch (HibernateException e) {e.printStackTrace();

}catch (Exception ex) { ex.printStackTrace(); }

}

}

Page 195: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

195

Run the Test and you should see the following results.

*** Session connect status: true18:54:06,796 DEBUG SQL:401 - select pet0_.PET_ID as PET1_0_0_,pet0_.VERSION as VERSION0_0_, pet0_.LICENSE as LICENSE0_0_, pet0_.NAMEas NAME0_0_, pet0_.DESCRIPTION as DESCRIPT5_0_0_, pet0_.BIRTH_DATE asBIRTH6_0_0_, pet0_.PRICE as PRICE0_0_, pet0_1_.TRICKS as TRICKS2_0_,case when pet0_1_.PET_ID is not null then 1 when pet0_.PET_ID is notnull then 0 else -1 end as clazz_0_ from PET pet0_ left outer join DOGpet0_1_ on pet0_.PET_ID=pet0_1_.PET_ID where pet0_.PET_ID=?Hibernate: select pet0_.PET_ID as PET1_0_0_, pet0_.VERSION asVERSION0_0_, pet0_.LICENSE as LICENSE0_0_, pet0_.NAME as NAME0_0_,pet0_.DESCRIPTION as DESCRIPT5_0_0_, pet0_.BIRTH_DATE as BIRTH6_0_0_,pet0_.PRICE as PRICE0_0_, pet0_1_.TRICKS as TRICKS2_0_, case whenpet0_1_.PET_ID is not null then 1 when pet0_.PET_ID is not null then 0else -1 end as clazz_0_ from PET pet0_ left outer join DOG pet0_1_ onpet0_.PET_ID=pet0_1_.PET_ID where pet0_.PET_ID=?18:54:06,796 DEBUG LongType:133 - binding '1' to parameter: 118:54:06,812 DEBUG IntegerType:172 - returning '1' as column: clazz_0_18:54:06,812 DEBUG IntegerType:172 - returning '1' as column:VERSION0_0_18:54:06,812 DEBUG StringType:172 - returning 'LIC00000' as column:LICENSE0_0_18:54:06,812 DEBUG StringType:172 - returning 'Fido' as column:NAME0_0_18:54:06,812 DEBUG StringType:172 - returning 'Dog' as column:DESCRIPT5_0_0_18:54:06,828 DEBUG DateType:172 - returning '04 January 1992' ascolumn: BIRTH6_0_0_18:54:06,828 DEBUG BigDecimalType:172 - returning '19.95' as column:PRICE0_0_18:54:06,828 DEBUG StringType:172 - returning 'Sit, Play Dead' ascolumn: TRICKS2_0_18:54:06,875 DEBUG SQL:401 - select inventoryr0_.PET_ID as PET5_1_,inventoryr0_.INVENTORY_ID as INVENTORY1_1_, inventoryr0_.INVENTORY_IDas INVENTORY1_3_0_, inventoryr0_.VERSION as VERSION3_0_,inventoryr0_.location as location3_0_, inventoryr0_.quantity asquantity3_0_, inventoryr0_.PET_ID as PET5_3_0_ from INVENTORYinventoryr0_ where inventoryr0_.PET_ID=?Hibernate: select inventoryr0_.PET_ID as PET5_1_,inventoryr0_.INVENTORY_ID as INVENTORY1_1_, inventoryr0_.INVENTORY_IDas INVENTORY1_3_0_, inventoryr0_.VERSION as VERSION3_0_,inventoryr0_.location as location3_0_, inventoryr0_.quantity asquantity3_0_, inventoryr0_.PET_ID as PET5_3_0_ from INVENTORYinventoryr0_ where inventoryr0_.PET_ID=?18:54:06,890 DEBUG LongType:133 - binding '1' to parameter: 118:54:06,890 DEBUG LongType:172 - returning '1' as column:INVENTORY1_3_0_18:54:06,890 DEBUG IntegerType:172 - returning '1' as column:VERSION3_0_

Page 196: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

196

18:54:06,890 DEBUG StringType:172 - returning 'Dallas' as column:location3_0_18:54:06,906 DEBUG IntegerType:172 - returning '10' as column:quantity3_0_18:54:06,906 DEBUG LongType:172 - returning '1' as column: PET5_3_0_18:54:06,906 DEBUG LongType:172 - returning '1' as column: PET5_1_18:54:06,906 DEBUG LongType:172 - returning '1' as column:INVENTORY1_1_18:54:06,906 DEBUG LongType:172 - returning '2' as column:INVENTORY1_3_0_18:54:06,906 DEBUG IntegerType:172 - returning '1' as column:VERSION3_0_18:54:06,906 DEBUG StringType:172 - returning 'Ft Worth' as column:location3_0_18:54:06,906 DEBUG IntegerType:172 - returning '20' as column:quantity3_0_18:54:06,906 DEBUG LongType:172 - returning '1' as column: PET5_3_0_18:54:06,906 DEBUG LongType:172 - returning '1' as column: PET5_1_18:54:06,906 DEBUG LongType:172 - returning '2' as column:INVENTORY1_1_Inventory: 1, Ft Worth, 20Inventory: 1, Dallas, 10After commit session open state = false

Page 197: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

197

Lab 24 – JNDI, Connection Pool, Web Application and Hibernate

Create a simple DBCP Connection Pool in Tomcat.

DBCP uses the Jakarta-Commons Database Connection Pool. It relies on number ofJakarta-Commons components:

Jakarta-Commons DBCP Jakarta-Commons Collections Jakarta-Commons Pool

Copy the derbyclient.jar file to C:\apache-tomcat-5.5.26\common\lib.

Page 198: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

198

Start the Tomcat Server.

Page 199: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

199

Add the Project to the Server.

Page 200: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

200

Add the Project.

Page 201: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

201

Restart Tomcat.

Page 202: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

202

Open server.xml in the Servers folder and go to the bottom of the file to find thefollowing.

<Context docBase="HibernateWebProject"path="/HibernateWebProject"reloadable="true"source=

"org.eclipse.jst.j2ee.server:HibernateWebProject"/>

Edit the Context to include the following.

<Context docBase="HibernateWebProject"path="/HibernateWebProject"reloadable="true"source="org.eclipse.jst.j2ee.server:HibernateWebProject">

<Resource name="jdbc/PetDB"auth="Container"type="javax.sql.DataSource"maxActive="100"maxIdle="30"maxWait="10000"username="user"password="password"driverClassName="org.apache.derby.jdbc.ClientDriver"url="jdbc:derby://localhost:1527/PetDB"/>

</Context>

Page 203: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

203

Update web.xml to include the following.

<?xml version="1.0" encoding="UTF-8"?><web-app id="WebApp_ID" 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/j2eehttp://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

<display-name>HibernateWebProject</display-name>

<resource-ref><description>DB Connection</description><res-ref-name>jdbc/PetDB</res-ref-name><res-type>javax.sql.DataSource</res-type><res-auth>Container</res-auth>

</resource-ref>

<welcome-file-list><welcome-file>index.html</welcome-file><welcome-file>index.htm</welcome-file><welcome-file>index.jsp</welcome-file><welcome-file>default.html</welcome-file><welcome-file>default.htm</welcome-file><welcome-file>default.jsp</welcome-file>

</welcome-file-list></web-app>

Page 204: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

204

Import the following JAR files to the WEB-INF\lib folder.

Page 205: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

205

Create a simple JSP named test.jsp to test the connection.

Page 206: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

206

Add the following code.

<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<sql:query var="rs" dataSource="jdbc/PetDB">SELECT PET_ID, NAME FROM PET</sql:query>

<html><head>

<title>DB Test</title></head><body>

<h2>Results</h2>

<c:forEach var="row" items="${rs.rows}">ID ${row.PET_ID}<br/>Name ${row.NAME}<br/>

</c:forEach>

</body></html>

Page 207: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

207

Run test.jsp on the Server and you should see the following.

Page 208: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

208

Using a Servlet.

Create a new package named servlets.

Page 209: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

209

Create a new Servlet named TestServlet

Page 210: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

210

Add the following code.

package servlets;

import java.io.IOException;import java.io.PrintWriter;import java.sql.Connection;import java.sql.ResultSet;import java.sql.Statement;

import javax.naming.InitialContext;import javax.servlet.ServletException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.sql.DataSource;

/*** Servlet implementation class for Servlet: TestServlet**/public class TestServlet extends

javax.servlet.http.HttpServletimplements javax.servlet.Servlet {

static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request,HttpServletResponse response)

throws ServletException, IOException {response.setContentType("text/html");PrintWriter out = response.getWriter();out.println("<HTML>");out.println("<HEAD>");out.println("<TITLE>Test JNDI</TITLE>");out.println("</HEAD>");out.println("<BODY>");

try {InitialContext initCtx =

new InitialContext();DataSource ds = (DataSource)

initCtx.lookup("java:comp/env/jdbc/PetDB");Connection conn = ds.getConnection();

out.println("<br><br>");out.println(

"Connection from DataSource successfully opened!<br>");

Page 211: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

211

Statement stmt = conn.createStatement();ResultSet rs = stmt.executeQuery(

"select * from PET");

while (rs.next() ) {String onerow = "Pet ID: " + rs.getString("PET_ID")

+ ", Name: " + rs.getString("NAME")+ ", Description: " + rs.getString("DESCRIPTION") +"<br>";

out.println(onerow);}

rs.close();stmt.close();conn.close();initCtx.close();

out.println("<br><br>");out.println(

"Connection from DataSource successfully closed!<br>");}catch(Exception e) {

out.println("<br><br>");out.println(

"Connection from DataSource NOT successfully opened!<br>");out.println(e.getMessage() + "<br>");

}

out.println(" </BODY>");out.println("</HTML>");out.flush();out.close();

}

}

Page 212: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

212

Run the Servlet on the Server and you should see the following.

Page 213: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

213

Use Hibernate with the Tomcat Connection Pool.

Create a ServletContextListener as below.

Page 214: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

214

Add the following.

package servlets;

import javax.servlet.ServletContextListener;import javax.servlet.ServletContextEvent;

public class HibernateAppListener implements ServletContextListener{

/* Application Startup Event */public void contextInitialized(ServletContextEvent ce) {

System.out.println("Connect");

try {System.out.println(

"In HibernateAppListener.contextInitialized");

Class.forName("utils.HibernateUtil").newInstance();

System.out.println("In HibernateAppListener, " +"Class.forName for utils.HibernateUtil successful");

}catch (Exception e) {

System.out.println("In HibernateAppListener, " +" Class.forName for utils.HibernateUtil throws Exception");

}}

/* Application Shutdown Event */public void contextDestroyed(ServletContextEvent ce) {}

}

Page 215: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

215

Create a new Servlet.

package servlets;

import java.io.IOException;import java.io.PrintWriter;import java.util.Iterator;import javax.servlet.ServletException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.hibernate.Query;import org.hibernate.Session;import pets.Pet;

import utils.HibernateUtil;

public class HibernateServlet extendsjavax.servlet.http.HttpServletimplements javax.servlet.Servlet {static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request,HttpServletResponse response)

throws ServletException, IOException {response.setContentType("text/html");PrintWriter out = response.getWriter();out.println("<HTML>");out.println("<HEAD>");out.println("<TITLE>Test JNDI</TITLE>");out.println("</HEAD>");out.println("<BODY>");

try {Session session =HibernateUtil.getSessionFactory().openSession();

session.beginTransaction();

String SQL_QUERY = "FROM Pet";Query query = session.createQuery(SQL_QUERY);for(Iterator it=query.iterate(); it.hasNext(); ) {

Pet pet=(Pet)it.next();out.println(pet + ("<BR>");

}

session.getTransaction().commit();

Page 216: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

216

}catch(Exception e) {

out.println("<br><br>");out.println(

"Connection from DataSource NOT successfully opened!<br>");out.println(e.getMessage() + "<br>");

}

out.println(" </BODY>");out.println("</HTML>");out.flush();out.close();

}

}

Page 217: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

217

Update web.xml

<listener><listener-class>servlets.HibernateAppListener</listener-class>

</listener>

Page 218: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

218

Update hibernate.cfg.xml

<?xml version="1.0" encoding="utf-8"?><!DOCTYPE hibernate-configuration PUBLIC

"-//Hibernate/Hibernate Configuration DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

<!-- SessionFactory --><session-factory>

<!-- Use a Tomcat JNDI datasource --><property name="connection.datasource">

java:comp/env/jdbc/PetDB</property>

<!-- Properties --><!-- Comment Out the following<property name="hibernate.connection.url">

jdbc:derby://localhost:1527/PetDB</property><property name="hibernate.connection.driver_class">

org.apache.derby.jdbc.ClientDriver</property><property name="hibernate.connection.username">

user</property><property name="hibernate.connection.password">

password</property>-->

<property name="hibernate.dialect">org.hibernate.dialect.DerbyDialect

</property><property name="hibernate.connection.pool_size">

1</property>

<!-- Echo SQL --><property name="hibernate.show_sql">

True</property>

Page 219: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

219

<!-- Use Thread local contextual sessions --><property name="hibernate.current_session_context_class">

thread</property>

<!-- Configure Cache --><property name="hibernate.cache.provider_class">

org.hibernate.cache.EhCacheProvider</property>

<!-- Mapping Files --><mapping resource="resources/Pet.hbm.xml"/><mapping resource="resources/Inventory.hbm.xml"/>

</session-factory>

</hibernate-configuration>

Page 220: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

220

Copy the Hibernate JARs to Tomcat.

Page 221: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

221

Run the Servlet on the Server and you should see the following.

Page 222: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

222

And in the Consloe.

ConnectIn HibernateAppListener.contextInitializedIn HibernateAppListener, Class.forName for utils.HibernateUtilsuccessfulHibernate: select pet0_.PET_ID as col_0_0_ from PET pet0_Hibernate: select pet0_.PET_ID as PET1_0_0_, pet0_.VERSION asVERSION0_0_, pet0_.LICENSE as LICENSE0_0_, pet0_.NAME as NAME0_0_,pet0_.DESCRIPTION as DESCRIPT5_0_0_, pet0_.BIRTH_DATE as BIRTH6_0_0_,pet0_.PRICE as PRICE0_0_, pet0_1_.TRICKS as TRICKS2_0_, case whenpet0_1_.PET_ID is not null then 1 when pet0_.PET_ID is not null then 0else -1 end as clazz_0_ from PET pet0_ left outer join DOG pet0_1_ onpet0_.PET_ID=pet0_1_.PET_ID where pet0_.PET_ID=?Hibernate: select pet0_.PET_ID as PET1_0_0_, pet0_.VERSION asVERSION0_0_, pet0_.LICENSE as LICENSE0_0_, pet0_.NAME as NAME0_0_,pet0_.DESCRIPTION as DESCRIPT5_0_0_, pet0_.BIRTH_DATE as BIRTH6_0_0_,pet0_.PRICE as PRICE0_0_, pet0_1_.TRICKS as TRICKS2_0_, case whenpet0_1_.PET_ID is not null then 1 when pet0_.PET_ID is not null then 0else -1 end as clazz_0_ from PET pet0_ left outer join DOG pet0_1_ onpet0_.PET_ID=pet0_1_.PET_ID where pet0_.PET_ID=?Hibernate: select pet0_.PET_ID as PET1_0_0_, pet0_.VERSION asVERSION0_0_, pet0_.LICENSE as LICENSE0_0_, pet0_.NAME as NAME0_0_,pet0_.DESCRIPTION as DESCRIPT5_0_0_, pet0_.BIRTH_DATE as BIRTH6_0_0_,pet0_.PRICE as PRICE0_0_, pet0_1_.TRICKS as TRICKS2_0_, case whenpet0_1_.PET_ID is not null then 1 when pet0_.PET_ID is not null then 0else -1 end as clazz_0_ from PET pet0_ left outer join DOG pet0_1_ onpet0_.PET_ID=pet0_1_.PET_ID where pet0_.PET_ID=?Hibernate: select pet0_.PET_ID as PET1_0_0_, pet0_.VERSION asVERSION0_0_, pet0_.LICENSE as LICENSE0_0_, pet0_.NAME as NAME0_0_,pet0_.DESCRIPTION as DESCRIPT5_0_0_, pet0_.BIRTH_DATE as BIRTH6_0_0_,pet0_.PRICE as PRICE0_0_, pet0_1_.TRICKS as TRICKS2_0_, case whenpet0_1_.PET_ID is not null then 1 when pet0_.PET_ID is not null then 0else -1 end as clazz_0_ from PET pet0_ left outer join DOG pet0_1_ onpet0_.PET_ID=pet0_1_.PET_ID where pet0_.PET_ID=?Hibernate: select pet0_.PET_ID as PET1_0_0_, pet0_.VERSION asVERSION0_0_, pet0_.LICENSE as LICENSE0_0_, pet0_.NAME as NAME0_0_,

Page 223: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

223

pet0_.DESCRIPTION as DESCRIPT5_0_0_, pet0_.BIRTH_DATE as BIRTH6_0_0_,pet0_.PRICE as PRICE0_0_, pet0_1_.TRICKS as TRICKS2_0_, case whenpet0_1_.PET_ID is not null then 1 when pet0_.PET_ID is not null then 0else -1 end as clazz_0_ from PET pet0_ left outer join DOG pet0_1_ onpet0_.PET_ID=pet0_1_.PET_ID where pet0_.PET_ID=?Hibernate: select pet0_.PET_ID as PET1_0_0_, pet0_.VERSION asVERSION0_0_, pet0_.LICENSE as LICENSE0_0_, pet0_.NAME as NAME0_0_,pet0_.DESCRIPTION as DESCRIPT5_0_0_, pet0_.BIRTH_DATE as BIRTH6_0_0_,pet0_.PRICE as PRICE0_0_, pet0_1_.TRICKS as TRICKS2_0_, case whenpet0_1_.PET_ID is not null then 1 when pet0_.PET_ID is not null then 0else -1 end as clazz_0_ from PET pet0_ left outer join DOG pet0_1_ onpet0_.PET_ID=pet0_1_.PET_ID where pet0_.PET_ID=?Hibernate: select pet0_.PET_ID as PET1_0_0_, pet0_.VERSION asVERSION0_0_, pet0_.LICENSE as LICENSE0_0_, pet0_.NAME as NAME0_0_,pet0_.DESCRIPTION as DESCRIPT5_0_0_, pet0_.BIRTH_DATE as BIRTH6_0_0_,pet0_.PRICE as PRICE0_0_, pet0_1_.TRICKS as TRICKS2_0_, case whenpet0_1_.PET_ID is not null then 1 when pet0_.PET_ID is not null then 0else -1 end as clazz_0_ from PET pet0_ left outer join DOG pet0_1_ onpet0_.PET_ID=pet0_1_.PET_ID where pet0_.PET_ID=?Hibernate: select pet0_.PET_ID as PET1_0_0_, pet0_.VERSION asVERSION0_0_, pet0_.LICENSE as LICENSE0_0_, pet0_.NAME as NAME0_0_,pet0_.DESCRIPTION as DESCRIPT5_0_0_, pet0_.BIRTH_DATE as BIRTH6_0_0_,pet0_.PRICE as PRICE0_0_, pet0_1_.TRICKS as TRICKS2_0_, case whenpet0_1_.PET_ID is not null then 1 when pet0_.PET_ID is not null then 0else -1 end as clazz_0_ from PET pet0_ left outer join DOG pet0_1_ onpet0_.PET_ID=pet0_1_.PET_ID where pet0_.PET_ID=?Hibernate: select pet0_.PET_ID as PET1_0_0_, pet0_.VERSION asVERSION0_0_, pet0_.LICENSE as LICENSE0_0_, pet0_.NAME as NAME0_0_,pet0_.DESCRIPTION as DESCRIPT5_0_0_, pet0_.BIRTH_DATE as BIRTH6_0_0_,pet0_.PRICE as PRICE0_0_, pet0_1_.TRICKS as TRICKS2_0_, case whenpet0_1_.PET_ID is not null then 1 when pet0_.PET_ID is not null then 0else -1 end as clazz_0_ from PET pet0_ left outer join DOG pet0_1_ onpet0_.PET_ID=pet0_1_.PET_ID where pet0_.PET_ID=?Hibernate: select pet0_.PET_ID as PET1_0_0_, pet0_.VERSION asVERSION0_0_, pet0_.LICENSE as LICENSE0_0_, pet0_.NAME as NAME0_0_,pet0_.DESCRIPTION as DESCRIPT5_0_0_, pet0_.BIRTH_DATE as BIRTH6_0_0_,pet0_.PRICE as PRICE0_0_, pet0_1_.TRICKS as TRICKS2_0_, case whenpet0_1_.PET_ID is not null then 1 when pet0_.PET_ID is not null then 0else -1 end as clazz_0_ from PET pet0_ left outer join DOG pet0_1_ onpet0_.PET_ID=pet0_1_.PET_ID where pet0_.PET_ID=?

Page 224: Hibernate Quick Start - Marathon Technology, Inc. Quick Start.pdf · 1 Hibernate Quick Start For the labs we will be using the following: Hibernate 3.2.6 Hibernate Tools JDK 1.5.0.15

224