• No results found

This tutorial will teach you how to use Hibernate to develop your database based web applications in simple and easy steps.

N/A
N/A
Protected

Academic year: 2021

Share "This tutorial will teach you how to use Hibernate to develop your database based web applications in simple and easy steps."

Copied!
218
0
0

Loading.... (view fulltext now)

Full text

(1)
(2)

i

About the Tutorial

Hibernate is a high-performance Object/Relational persistence and query service, which is licensed under the open source GNU Lesser General Public License (LGPL) and is free to download. Hibernate not only takes care of the mapping from Java classes to database tables (and from Java data types to SQL data types), but also provides data query and retrieval facilities.

This tutorial will teach you how to use Hibernate to develop your database based web applications in simple and easy steps.

Audience

This tutorial is designed for all those Java programmers who would like to understand the Hibernate framework and its API.

Prerequisites

We assume you have a good understanding of the Java programming language. A basic understanding of relational databases, JDBC, and SQL will be very helpful in understanding this tutorial.

Copyright & Disclaimer

© Copyright 2015 by Tutorials Point (I) Pvt. Ltd.

All the content and graphics published in this e-book are the property of Tutorials Point (I) Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish any contents or a part of the contents of this e-book in any manner without written consent of the publisher.

We strive to update the contents of our website and tutorials as timely and as precisely as possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt. Ltd. provides no guarantee regarding the accuracy, timeliness, or completeness of our website or its contents including this tutorial. If you discover any errors on our website or in this tutorial, please notify us at contact@tutorialspoint.com

(3)

ii

Table of Contents

About the Tutorial ... i

Audience ... i

Prerequisites ... i

Copyright & Disclaimer ... i

Table of Contents ... ii

1.

HIBERNATE – ORM OVERVIEW ... 1

What is JDBC? ... 1

Pros and Cons of JDBC ... 1

Why Object Relational Mapping (ORM)? ... 1

What is ORM? ... 3

Java ORM Frameworks ... 4

2.

HIBERNATE – OVERVIEW ... 5

Hibernate Advantages ... 5 Supported Databases ... 6 Supported Technologies ... 6

3.

HIBERNATE ARCHITECTURE ... 7

Configuration Object ... 8 SessionFactory Object ... 9 Session Object ... 9 Transaction Object ... 9 Query Object ... 9 Criteria Object ... 9

4.

HIBERNATE – ENVIRONMENT SETUP ... 10

Downloading Hibernate ... 10

(4)

iii

Hibernate Prerequisites ... 11

5.

HIBERNATE – CONFIGURATION ... 12

Hibernate with MySQL Database ... 13

6.

HIBERNATE – SESSIONS ... 16

Session Interface Methods ... 17

7.

HIBERNATE – PERSISTENT CLASS ... 19

Simple POJO Example ... 19

8.

HIBERNATE – MAPPING FILES ... 21

9.

HIBERNATE – MAPPING TYPES ... 24

Primitive Types ... 24

Date and Time Types ... 24

Binary and Large Object Types ... 24

JDK-related Types ... 25

10.

HIBERNATE – EXAMPLES ... 26

Create POJO Classes ... 26

Create Database Tables ... 27

Create Mapping Configuration File ... 27

Create Application Class ... 29

Compilation and Execution ... 32

11.

HIBERNATE – O/R MAPPINGS ... 34

Collections Mappings ... 34

Hibernate – Set Mappings ... 35

Hibernate – SortedSet Mappings ... 45

Hibernate – List Mappings ... 57

(5)

iv

Hibernate – Map Mappings ... 78

Hibernate – SortedMap Mappings ... 88

Association Mappings ... 100

Hibernate – Many-to-One Mappings ... 100

Hibernate – One-to-One Mappings ... 111

Hibernate – One-to-Many Mappings ... 122

Hibernate – Many-to-Many Mappings ... 133

Component Mappings ... 144

Hibernate – Component Mappings ... 145

12.

HIBERNATE – ANNOTATIONS ... 156

Environment Setup for Hibernate Annotation ... 156

Annotated Class Example ... 156

@Entity Annotation ... 158

@Table Annotation... 158

@Id and @GeneratedValue Annotations ... 158

@Column Annotation... 159

Create Application Class ... 159

Database Configuration ... 162

Compilation and Execution ... 163

13.

HIBERNATE – QUERY LANGUAGE ... 165

FROM Clause ... 165 AS Clause ... 165 SELECT Clause ... 166 WHERE Clause ... 166 ORDER BY Clause ... 166 GROUP by Clause ... 167

(6)

v

UPDATE Clause ... 167

DELETE Clause ... 168

INSERT Clause ... 168

Aggregate Methods ... 168

Pagination using Query ... 169

14.

HIBERNATE – CRITERIA QUERIES ... 170

Restrictions with Criteria ... 170

Pagination Using Criteria ... 172

Sorting the Results ... 172

Projections & Aggregations ... 172

Criteria Queries Example ... 173

Compilation and Execution ... 179

15.

HIBERNATE – NATIVE SQL ... 181

Scalar Queries ... 181

Entity Queries ... 181

Named SQL Queries ... 181

Native SQL Example ... 182

Compilation and Execution ... 187

16.

HIBERNATE – CACHING ... 189

First-level Cache ... 189

Second-level Cache ... 189

Query-level Cache ... 190

The Second Level Cache ... 190

Concurrency Strategies ... 190

Cache Provider ... 191

(7)

vi

17.

HIBERNATE – BATCH PROCESSING ... 195

Batch Processing Example ... 196

Compilation and Execution ... 201

18.

HIBERNATE – INTERCEPTORS ... 202

How to Use Interceptors? ... 202

Create POJO Classes ... 204

Create Database Tables ... 206

Create Mapping Configuration File ... 206

Create Application Class ... 207

(8)

1

What is JDBC?

JDBC stands for Java Database Connectivity. It provides a set of Java API for accessing the relational databases from Java program. These Java APIs enables Java programs to execute SQL statements and interact with any SQL compliant database.

JDBC provides a flexible architecture to write a database independent application that can run on different platforms and interact with different DBMS without any modification.

Pros and Cons of JDBC

Pros of JDBC Cons of JDBC

Clean and simple SQL processing Complex if it is used in large projects Good performance with large data Large programming overhead

Very good for small applications No encapsulation

Simple syntax so easy to learn Hard to implement MVC concept. Query is DBMS specific.

Why Object Relational Mapping (ORM)?

When we work with an object-oriented system, there is a mismatch between the object model and the relational database. RDBMSs represent data in a tabular format whereas object-oriented languages, such as Java or C# represent it as an interconnected graph of objects.

Consider the following Java Class with proper constructors and associated public function:

public class Employee { private int id;

private String first_name; private String last_name; private int salary;

public Employee() {}

public Employee(String fname, String lname, int salary) { this.first_name = fname;

this.last_name = lname; this.salary = salary;

(9)

2

}

public int getId() { return id;

}

public String getFirstName() { return first_name;

}

public String getLastName() { return last_name;

}

public int getSalary() { return salary;

} }

Consider the above objects are to be stored and retrieved into the following RDBMS table:

create table EMPLOYEE (

id INT NOT NULL auto_increment, first_name VARCHAR(20) default NULL, last_name VARCHAR(20) default NULL, salary INT default NULL,

PRIMARY KEY (id) );

First problem, what if we need to modify the design of our database after having developed a few pages or our application? Second, loading and storing objects in a relational database exposes us to the following five mismatch problems:

Mismatch Description

Granularity Sometimes you will have an object model, which has more classes than the number of corresponding tables in the database.

Inheritance RDBMSs do not define anything similar to Inheritance, which is a natural paradigm in object-oriented programming languages.

Identity An RDBMS defines exactly one notion of 'sameness': the primary key. Java, however, defines both object identity (a==b) and object equality (a.equals(b)).

Associations Object-oriented languages represent associations using object references whereas an RDBMS represents an association as a foreign key column.

(10)

3 Navigation The ways you access objects in Java and in RDBMS are fundamentally different.

The Object-Relational Mapping (ORM) is the solution to handle all the above impedance mismatches.

What is ORM?

ORM stands for Object-Relational Mapping (ORM) is a programming technique for converting data between relational databases and object oriented programming languages such as Java, C#, etc.

An ORM system has the following advantages over plain JDBC:

S.N. Advantages

1 Let’s business code access objects rather than DB tables. 2 Hides details of SQL queries from OO logic.

3 Based on JDBC 'under the hood.'

4 No need to deal with the database implementation.

5 Entities based on business concepts rather than database structure. 6 Transaction management and automatic key generation.

7 Fast development of application.

An ORM solution consists of the following four entities:

S.N. Solutions

1 An API to perform basic CRUD operations on objects of persistent classes. 2 A language or API to specify queries that refer to classes and properties of classes. 3 A configurable facility for specifying mapping metadata.

(11)

4

Java ORM Frameworks

There are several persistent frameworks and ORM options in Java. A persistent framework is an ORM service that stores and retrieves objects into a relational database.

 Enterprise JavaBeans Entity Beans  Java Data Objects

 Castor  TopLink  Spring DAO

(12)

5 Hibernate is an Object-Relational Mapping(ORM) solution for JAVA. It is an open source persistent framework created by Gavin King in 2001. It is a powerful, high performance Object-Relational Persistence and Query service for any Java Application.

Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieves the developer from 95% of common data persistence related programming tasks.

Hibernate sits between traditional Java objects and database server to handle all the works in persisting those objects based on the appropriate O/R mechanisms and patterns.

Hibernate Advantages

 Hibernate takes care of mapping Java classes to database tables using XML files and without writing any line of code.

 Provides simple APIs for storing and retrieving Java objects directly to and from the database.

 If there is change in the database or in any table, then you need to change the XML file properties only.

 Abstracts away the unfamiliar SQL types and provides a way to work around familiar Java Objects.

 Hibernate does not require an application server to operate.  Manipulates Complex associations of objects of your database.  Minimizes database access with smart fetching strategies.  Provides simple querying of data.

(13)

6

Supported Databases

Hibernate supports almost all the major RDBMS. Following is a list of few of the database engines supported by Hibernate:

 HSQL Database Engine  DB2/NT  MySQL  PostgreSQL  FrontBase  Oracle

 Microsoft SQL Server Database  Sybase SQL Server

 Informix Dynamic Server

Supported Technologies

Hibernate supports a variety of other technologies, including:  XDoclet Spring

 J2EE

 Eclipse plug-ins  Maven

(14)

7 Hibernate has a layered architecture which helps the user to operate without having to know the underlying APIs. Hibernate makes use of the database and configuration data to provide persistence services (and persistent objects) to the application.

(15)

8 Following is a detailed view of the Hibernate Application Architecture with its important core classes.

Hibernate uses various existing Java APIs, like JDBC, Java Transaction API(JTA), and Java Naming and Directory Interface (JNDI). JDBC provides a rudimentary level of abstraction of functionality common to relational databases, allowing almost any database with a JDBC driver to be supported by Hibernate. JNDI and JTA allow Hibernate to be integrated with J2EE application servers.

Following section gives brief description of each of the class objects involved in Hibernate Application Architecture.

Configuration Object

The Configuration object is the first Hibernate object you create in any Hibernate application. It is usually created only once during application initialization. It represents a configuration or properties file required by the Hibernate.

The Configuration object provides two keys components:

Database Connection: This is handled through one or more configuration files

supported by Hibernate. These files are hibernate.properties and hibernate.cfg.xml.

Class Mapping Setup: This component creates the connection between the Java

(16)

9

SessionFactory Object

Configuration object is used to create a SessionFactory object which in turn configures Hibernate for the application using the supplied configuration file and allows for a Session object to be instantiated. The SessionFactory is a thread safe object and used by all the threads of an application.

The SessionFactory is a heavyweight object; it is usually created during application start up and kept for later use. You would need one SessionFactory object per database using a separate configuration file. So, if you are using multiple databases, then you would have to create multiple SessionFactory objects.

Session Object

A Session is used to get a physical connection with a database. The Session object is lightweight and designed to be instantiated each time an interaction is needed with the database. Persistent objects are saved and retrieved through a Session object.

The session objects should not be kept open for a long time because they are not usually thread safe and they should be created and destroyed them as needed.

Transaction Object

A Transaction represents a unit of work with the database and most of the RDBMS supports transaction functionality. Transactions in Hibernate are handled by an underlying transaction manager and transaction (from JDBC or JTA).

This is an optional object and Hibernate applications may choose not to use this interface, instead managing transactions in their own application code.

Query Object

Query objects use SQL or Hibernate Query Language (HQL) string to retrieve data from the database and create objects. A Query instance is used to bind query parameters, limit the number of results returned by the query, and finally to execute the query.

Criteria Object

Criteria objects are used to create and execute object oriented criteria queries to retrieve objects.

(17)

10 This chapter explains how to install Hibernate and other associated packages to prepare an environment for the Hibernate applications. We will work with MySQL database to experiment with Hibernate examples, so make sure you already have a setup for MySQL database. For more detail on MySQL, you can check our MySQL Tutorial.

Downloading Hibernate

It is assumed that you already have the latest version of Java installed on your system. Following are the simple steps to download and install Hibernate on your system:

 Make a choice whether you want to install Hibernate on Windows, or Unix and then proceed to the next step to download .zip file for windows and .tz file for Unix.

 Download the latest version of Hibernate from

http://www.hibernate.org/downloads.

 At the time of writing this tutorial, I downloaded hibernate-distribution-3.6.4.Final and when you unzip the downloaded file, it will give you directory structure as shown in the following image:

Installing Hibernate

Once you downloaded and unzipped the latest version of the Hibernate Installation file, you need to perform following two simple steps. Make sure you are setting your CLASSPATH variable properly otherwise you will face problem while compiling your application.

 Now, copy all the library files from /lib into your CLASSPATH, and change your classpath variable to include all the JARs:

 Finally, copy hibernate3.jar file into your CLASSPATH. This file lies in the root directory of the installation and is the primary JAR that Hibernate needs to do its work.

(18)

11

Hibernate Prerequisites

Following is the list of the packages/libraries required by Hibernate and you should install them before starting with Hibernate. To install these packages, you will have to copy library files from/lib into your CLASSPATH, and change your CLASSPATH variable accordingly.

S.N. Packages/Libraries

1 dom4j - XML parsing www.dom4j.org/

2 Xalan - XSLT Processor http://xml.apache.org/xalan-j/

3 Xerces - The Xerces Java Parser http://xml.apache.org/xerces-j/

4 cglib - Appropriate changes to Java classes at runtime http://cglib.sourceforge.net/

5 log4j - Logging Framework http://logging.apache.org/log4j

6 Commons - Logging, Email etc. http://jakarta.apache.org/commons

(19)

12 Hibernate requires to know in advance — where to find the mapping information that defines how your Java classes relate to the database tables. Hibernate also requires a set of configuration settings related to database and other related parameters. All such information is usually supplied as a standard Java properties file called hibernate.properties, or as an XML file named hibernate.cfg.xml.

I will consider XML formatted file hibernate.cfg.xml to specify required Hibernate properties in my examples. Most of the properties take their default values and it is not required to specify them in the property file unless it is really required. This file is kept in the root directory of your application's classpath.

Hibernate Properties

Following is the list of important properties, you will be required to configure for a databases in a standalone situation:

S.N. Properties and Description

1 hibernate.dialect This property makes Hibernate generate the appropriate SQL for the chosen database.

2 hibernate.connection.driver_class The JDBC driver class.

3 hibernate.connection.url The JDBC URL to the database instance.

4 hibernate.connection.username The database username.

5 hibernate.connection.password The database password.

6 hibernate.connection.pool_size Limits the number of connections waiting in the Hibernate database connection pool.

(20)

13 If you are using a database along with an application server and JNDI, then you would have to configure the following properties:

S.N. Properties and Description

1 hibernate.connection.datasource The JNDI name defined in the application server context, which you are using for the application.

2 hibernate.jndi.class The InitialContext class for JNDI.

3 hibernate.jndi.<JNDIpropertyname> Passes any JNDI property you like to the JNDI InitialContext.

4 hibernate.jndi.url

Provides the URL for JNDI.

5 hibernate.connection.username The database username.

6 hibernate.connection.password The database password.

Hibernate with MySQL Database

MySQL is one of the most popular open-source database systems available today. Let us create hibernate.cfg.xml configuration file and place it in the root of your application's classpath. You will have to make sure that you have testdb database available in your MySQL database and you have a user test available to access the database.

The XML configuration file must conform to the Hibernate 3 Configuration DTD, which is available at http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd.

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

"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.dialect"> org.hibernate.dialect.MySQLDialect </property> <property name="hibernate.connection.driver_class"> com.mysql.jdbc.Driver </property>

(21)

14 <property name="hibernate.connection.url"> jdbc:mysql://localhost/test </property> <property name="hibernate.connection.username"> root </property> <property name="hibernate.connection.password"> root123 </property>

<!-- List of XML mapping files --> <mapping resource="Employee.hbm.xml"/> </session-factory>

</hibernate-configuration>

The above configuration file includes <mapping> tags, which are related to hibernate-mapping file and we will see in next chapter what exactly a hibernate hibernate-mapping file is and how and why do we use it?

Following is the list of various important databases dialect property type:

Database Dialect Property

DB2 org.hibernate.dialect.DB2Dialect HSQLDB org.hibernate.dialect.HSQLDialect HypersonicSQL org.hibernate.dialect.HSQLDialect Informix org.hibernate.dialect.InformixDialect Ingres org.hibernate.dialect.IngresDialect Interbase org.hibernate.dialect.InterbaseDialect Microsoft SQL Server 2000 org.hibernate.dialect.SQLServerDialect Microsoft SQL Server 2005 org.hibernate.dialect.SQLServer2005Dialect Microsoft SQL Server 2008 org.hibernate.dialect.SQLServer2008Dialect

MySQL org.hibernate.dialect.MySQLDialect

Oracle (any version) org.hibernate.dialect.OracleDialect Oracle 11g org.hibernate.dialect.Oracle10gDialect Oracle 10g org.hibernate.dialect.Oracle10gDialect

(22)

15 Oracle 9i org.hibernate.dialect.Oracle9iDialect PostgreSQL org.hibernate.dialect.PostgreSQLDialect Progress org.hibernate.dialect.ProgressDialect SAP DB org.hibernate.dialect.SAPDBDialect Sybase org.hibernate.dialect.SybaseDialect

(23)

16 A Session is used to get a physical connection with a database. The Session object is lightweight and designed to be instantiated each time an interaction is needed with the database. Persistent objects are saved and retrieved through a Session object.

The session objects should not be kept open for a long time because they are not usually thread safe and they should be created and destroyed them as needed. The main function of the Session is to offer, create, read, and delete operations for instances of mapped entity classes.

Instances may exist in one of the following three states at a given point in time:

transient: A new instance of a persistent class, which is not associated with a Session and has no representation in the database and no identifier value is considered transient by Hibernate.

persistent: You can make a transient instance persistent by associating it with a

Session. A persistent instance has a representation in the database, an identifier value and is associated with a Session.

detached: Once we close the Hibernate Session, the persistent instance will

become a detached instance.

A Session instance is serializable if its persistent classes are serializable. A typical transaction should use the following idiom:

Session session = factory.openSession(); Transaction tx = null; try { tx = session.beginTransaction(); // do some work ... tx.commit(); } catch (Exception e) { if (tx!=null) tx.rollback(); e.printStackTrace(); }finally { session.close(); }

If the Session throws an exception, the transaction must be rolled back and the session must be discarded.

(24)

17

Session Interface Methods

There are number of methods provided by the Session interface, but I'm going to list down a few important methods only, which we will use in this tutorial. You can check Hibernate documentation for a complete list of methods associated with Session and SessionFactory.

S.N. Session Methods and Description

1 Transaction beginTransaction() Begin a unit of work and return the associated Transaction object. 2 void cancelQuery() Cancel the execution of the current query.

3 void clear() Completely clear the session.

4 Connection close() End the session by releasing the JDBC connection and cleaning up.

5 Criteria createCriteria(Class persistentClass) Create a new Criteria instance, for the given entity class, or a superclass of an entity class.

6 Criteria createCriteria(String entityName) Create a new Criteria instance, for the given entity name.

7 Serializable getIdentifier(Object object) Return the identifier value of the given entity as associated with this session.

8 Query createFilter(Object collection, String queryString) Create a new instance of Query for the given collection and filter string. 9 Query createQuery(String queryString) Create a new instance of Query for the given HQL query string.

10 SQLQuery createSQLQuery(String queryString) Create a new instance of SQLQuery for the given SQL query string. 11 void delete(Object object) Remove a persistent instance from the datastore.

12 void delete(String entityName, Object object)

Remove a persistent instance from the datastore.

13 Session get(String entityName, Serializable id) Return the persistent instance of the given named entity with the given identifier, or null if there is no such persistent instance.

14 SessionFactory getSessionFactory() Get the session factory, which created this session.

15 void refresh(Object object) Re-read the state of the given instance from the underlying database. 16 Transaction getTransaction() Get the Transaction instance associated with this session.

(25)

18 18 boolean isDirty() Does this session contain any changes, which must be synchronized with the

database?

19 boolean isOpen() Check if the session is still open.

20 Serializable save(Object object) Persist the given transient instance, first assigning a generated identifier. 21 void saveOrUpdate(Object object) Either save(Object) or update(Object) the given instance.

22

void update(Object object)

Update the persistent instance with the identifier of the given detached instance.

23 void update(String entityName, Object object) Update the persistent instance with the identifier of the given detached instance.

(26)

19 The entire concept of Hibernate is to take the values from Java class attributes and persist them to a database table. A mapping document helps Hibernate in determining how to pull the values from the classes and map them with table and associated fields.

Java classes whose objects or instances will be stored in database tables are called persistent classes in Hibernate. Hibernate works best if these classes follow some simple rules, also known as the Plain Old Java Object (POJO) programming model.

There are following main rules of persistent classes, however, none of these rules are hard requirements:

 All Java classes that will be persisted need a default constructor.

 All classes should contain an ID in order to allow easy identification of your objects within Hibernate and the database. This property maps to the primary key column of a database table.

 All attributes that will be persisted should be declared private and have getXXX and setXXX methods defined in the JavaBean style.

 A central feature of Hibernate, proxies, depends upon the persistent class being either non-final, or the implementation of an interface that declares all public methods.

 All classes that do not extend or implement some specialized classes and interfaces required by the EJB framework.

The POJO name is used to emphasize that a given object is an ordinary Java Object, not a special object, and in particular not an Enterprise JavaBean.

Simple POJO Example

Based on the few rules mentioned above, we can define a POJO class as follows:

public class Employee { private int id;

private String firstName; private String lastName; private int salary; public Employee() {}

public Employee(String fname, String lname, int salary) { this.firstName = fname;

this.lastName = lname; this.salary = salary;

(27)

20

}

public int getId() { return id;

}

public void setId( int id ) { this.id = id;

}

public String getFirstName() { return firstName;

}

public void setFirstName( String first_name ) { this.firstName = first_name;

}

public String getLastName() { return lastName;

}

public void setLastName( String last_name ) { this.lastName = last_name;

}

public int getSalary() { return salary;

}

public void setSalary( int salary ) { this.salary = salary;

} }

(28)

21 An Object/relational mappings are usually defined in an XML document. This mapping file instructs Hibernate — how to map the defined class or classes to the database tables? Though many Hibernate users choose to write the XML by hand, but a number of tools exist to generate the mapping document. These include XDoclet, Middlegen, and AndroMDA for the advanced Hibernate users.

Let us consider our previously defined POJO class whose objects will persist in the table defined in next section.

public class Employee { private int id;

private String firstName; private String lastName; private int salary; public Employee() {}

public Employee(String fname, String lname, int salary) { this.firstName = fname;

this.lastName = lname; this.salary = salary; }

public int getId() { return id;

}

public void setId( int id ) { this.id = id;

}

public String getFirstName() { return firstName;

}

public void setFirstName( String first_name ) { this.firstName = first_name;

}

(29)

22

return lastName; }

public void setLastName( String last_name ) { this.lastName = last_name;

}

public int getSalary() { return salary;

}

public void setSalary( int salary ) { this.salary = salary;

} }

There would be one table corresponding to each object you are willing to provide persistence. Consider above objects need to be stored and retrieved into the following RDBMS table:

create table EMPLOYEE (

id INT NOT NULL auto_increment, first_name VARCHAR(20) default NULL, last_name VARCHAR(20) default NULL, salary INT default NULL,

PRIMARY KEY (id) );

Based on the two above entities, we can define following mapping file, which instructs Hibernate how to map the defined class or classes to the database tables.

<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"

"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping>

<class name="Employee" table="EMPLOYEE"> <meta attribute="class-description">

This class contains the employee detail. </meta>

(30)

23

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

<property name="firstName" column="first_name" type="string"/> <property name="lastName" column="last_name" type="string"/> <property name="salary" column="salary" type="int"/>

</class>

</hibernate-mapping>

You should save the mapping document in a file with the format <classname>.hbm.xml. We saved our mapping document in the file Employee.hbm.xml.

Let us see understand a little detail about the mapping elements used in the mapping file:  The mapping document is an XML document having <hibernate-mapping> as

the root element, which contains all the <class> elements.

 The <class> elements are used to define specific mappings from a Java classes to the database tables. The Java class name is specified using the name attribute of the class element and the database table name is specified using the table attribute.

 The <meta> element is optional element and can be used to create the class description.

 The <id> element maps the unique ID attribute in class to the primary key of the database table. The name attribute of the id element refers to the property in the class and the column attribute refers to the column in the database table. The type attribute holds the hibernate mapping type, this mapping types will convert from Java to SQL data type.

 The <generator> element within the id element is used to generate the primary key values automatically. The class attribute of the generator element is set to

native to let hibernate pick up either identity, sequence, or hilo algorithm to

create primary key depending upon the capabilities of the underlying database.  The <property> element is used to map a Java class property to a column in the

database table. The name attribute of the element refers to the property in the class and the column attribute refers to the column in the database table. The type attribute holds the hibernate mapping type, this mapping types will convert from Java to SQL data type.

There are other attributes and elements available, which will be used in a mapping document and I would try to cover as many as possible while discussing other Hibernate related topics.

(31)

24 When you prepare a Hibernate mapping document, you find that you map the Java data types into RDBMS data types. The types declared and used in the mapping files are not Java data types; they are not SQL database types either. These types are called Hibernate mapping types, which can translate from Java to SQL data types and vice versa.

This chapter lists down all the basic, date and time, large object, and various other built-in mappbuilt-ing types.

Primitive Types

Mapping type Java type ANSI SQL Type

integer int or java.lang.Integer INTEGER

long long or java.lang.Long BIGINT

short short or java.lang.Short SMALLINT

float float or java.lang.Float FLOAT

double double or java.lang.Double DOUBLE

big_decimal java.math.BigDecimal NUMERIC

character java.lang.String CHAR(1)

string java.lang.String VARCHAR

byte byte or java.lang.Byte TINYINT

boolean boolean or java.lang.Boolean BIT

yes/no boolean or java.lang.Boolean CHAR(1) ('Y' or 'N') true/false boolean or java.lang.Boolean CHAR(1) ('T' or 'F')

Date and Time Types

Mapping type Java type ANSI SQL Type

date java.util.Date or java.sql.Date DATE

time java.util.Date or java.sql.Time TIME

timestamp java.util.Date or java.sql.Timestamp TIMESTAMP

calendar java.util.Calendar TIMESTAMP

calendar_date java.util.Calendar DATE

Binary and Large Object Types

(32)

25

binary byte[] VARBINARY (or BLOB)

text java.lang.String CLOB

serializable any Java class that implements java.io.Serializable VARBINARY (or BLOB)

clob java.sql.Clob CLOB

blob java.sql.Blob BLOB

JDK-related Types

Mapping type Java type ANSI SQL Type

class java.lang.Class VARCHAR

locale java.util.Locale VARCHAR

timezone java.util.TimeZone VARCHAR

(33)

26 Let us now take an example to understand how we can use Hibernate to provide Java persistence in a standalone application. We will go through the different steps involved in creating a Java Application using Hibernate technology.

Create POJO Classes

The first step in creating an application is to build the Java POJO class or classes, depending on the application that will be persisted to the database. Let us consider our Employee class with getXXX and setXXX methods to make it JavaBeans compliant class. A POJO (Plain Old Java Object) is a Java object that doesn't extend or implement some specialized classes and interfaces respectively required by the EJB framework. All normal Java objects are POJO.

When you design a class to be persisted by Hibernate, it is important to provide JavaBeans compliant code as well as one attribute, which would work as index like id attribute in the Employee class.

public class Employee { private int id;

private String firstName; private String lastName; private int salary; public Employee() {}

public Employee(String fname, String lname, int salary) { this.firstName = fname;

this.lastName = lname; this.salary = salary; }

public int getId() { return id;

}

public void setId( int id ) { this.id = id;

}

(34)

27

return firstName; }

public void setFirstName( String first_name ) { this.firstName = first_name;

}

public String getLastName() { return lastName;

}

public void setLastName( String last_name ) { this.lastName = last_name;

}

public int getSalary() { return salary;

}

public void setSalary( int salary ) { this.salary = salary;

} }

Create Database Tables

Second step would be creating tables in your database. There would be one table corresponding to each object, you are willing to provide persistence. Consider above objects need to be stored and retrieved into the following RDBMS table:

create table EMPLOYEE (

id INT NOT NULL auto_increment, first_name VARCHAR(20) default NULL, last_name VARCHAR(20) default NULL, salary INT default NULL,

PRIMARY KEY (id) );

Create Mapping Configuration File

This step is to create a mapping file that instructs Hibernate how to map the defined class or classes to the database tables.

(35)

28

<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"

"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping>

<class name="Employee" table="EMPLOYEE"> <meta attribute="class-description">

This class contains the employee detail. </meta>

<id name="id" type="int" column="id"> <generator class="native"/>

</id>

<property name="firstName" column="first_name" type="string"/> <property name="lastName" column="last_name" type="string"/> <property name="salary" column="salary" type="int"/>

</class>

</hibernate-mapping>

You should save the mapping document in a file with the format <classname>.hbm.xml. We saved our mapping document in the file Employee.hbm.xml. Let us see little detail about the mapping document:

 The mapping document is an XML document having <hibernate-mapping> as the root element, which contains all the <class> elements.

 The <class> elements are used to define specific mappings from a Java classes to the database tables. The Java class name is specified using the name attribute of the class element and the database table name is specified using the table attribute.

 The <meta> element is optional element and can be used to create the class description.

 The <id> element maps the unique ID attribute in class to the primary key of the database table. The name attribute of the id element refers to the property in the class and the column attribute refers to the column in the database table. The type attribute holds the hibernate mapping type, this mapping types will convert from Java to SQL data type.

 The <generator> element within the id element is used to generate the primary key values automatically. The class attribute of the generator element is set to

native to let hibernate pick up either identity, sequence, or hilo algorithm to

create primary key depending upon the capabilities of the underlying database.  The <property> element is used to map a Java class property to a column in the

database table. The name attribute of the element refers to the property in the class and the column attribute refers to the column in the database table. The

(36)

29 type attribute holds the hibernate mapping type, this mapping types will convert from Java to SQL data type.

There are other attributes and elements available, which will be used in a mapping document and I would try to cover as many as possible while discussing other Hibernate related topics.

Create Application Class

Finally, we will create our application class with the main() method to run the application. We will use this application to save few Employee's records and then we will apply CRUD operations on those records.

import java.util.List; import java.util.Date; import java.util.Iterator; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class ManageEmployee {

private static SessionFactory factory; public static void main(String[] args) { try{

factory = new Configuration().configure().buildSessionFactory(); }catch (Throwable ex) {

System.err.println("Failed to create sessionFactory object." + ex); throw new ExceptionInInitializerError(ex);

}

ManageEmployee ME = new ManageEmployee(); /* Add few employee records in database */

Integer empID1 = ME.addEmployee("Zara", "Ali", 1000); Integer empID2 = ME.addEmployee("Daisy", "Das", 5000); Integer empID3 = ME.addEmployee("John", "Paul", 10000); /* List down all the employees */

(37)

30

ME.listEmployees();

/* Update employee's records */ ME.updateEmployee(empID1, 5000);

/* Delete an employee from the database */ ME.deleteEmployee(empID2);

/* List down new list of the employees */ ME.listEmployees();

}

/* Method to CREATE an employee in the database */

public Integer addEmployee(String fname, String lname, int salary){ Session session = factory.openSession();

Transaction tx = null; Integer employeeID = null; try{

tx = session.beginTransaction();

Employee employee = new Employee(fname, lname, salary); employeeID = (Integer) session.save(employee);

tx.commit(); }catch (HibernateException e) { if (tx!=null) tx.rollback(); e.printStackTrace(); }finally { session.close(); } return employeeID; }

/* Method to READ all the employees */ public void listEmployees( ){

Session session = factory.openSession(); Transaction tx = null;

try{

(38)

31

List employees = session.createQuery("FROM Employee").list(); for (Iterator iterator =

employees.iterator(); iterator.hasNext();){ Employee employee = (Employee) iterator.next();

System.out.print("First Name: " + employee.getFirstName()); System.out.print(" Last Name: " + employee.getLastName()); System.out.println(" Salary: " + employee.getSalary()); } tx.commit(); }catch (HibernateException e) { if (tx!=null) tx.rollback(); e.printStackTrace(); }finally { session.close(); } }

/* Method to UPDATE salary for an employee */

public void updateEmployee(Integer EmployeeID, int salary ){ Session session = factory.openSession();

Transaction tx = null; try{ tx = session.beginTransaction(); Employee employee = (Employee)session.get(Employee.class, EmployeeID); employee.setSalary( salary ); session.update(employee); tx.commit(); }catch (HibernateException e) { if (tx!=null) tx.rollback(); e.printStackTrace(); }finally { session.close(); } }

(39)

32

public void deleteEmployee(Integer EmployeeID){ Session session = factory.openSession(); Transaction tx = null; try{ tx = session.beginTransaction(); Employee employee = (Employee)session.get(Employee.class, EmployeeID); session.delete(employee); tx.commit(); }catch (HibernateException e) { if (tx!=null) tx.rollback(); e.printStackTrace(); }finally { session.close(); } } }

Compilation and Execution

Here are the steps to compile and run the above mentioned application. Make sure, you have set PATH and CLASSPATH appropriately before proceeding for the compilation and execution.

 Create hibernate.cfg.xml configuration file as explained in configuration chapter.  Create Employee.hbm.xml mapping file as shown above.

 Create Employee.java source file as shown above and compile it.

 Create ManageEmployee.java source file as shown above and compile it.  Execute ManageEmployee binary to run the program.

You would get the following result, and records would be created in the EMPLOYEE table.

$java ManageEmployee

...VARIOUS LOG MESSAGES WILL DISPLAY HERE... First Name: Zara Last Name: Ali Salary: 1000

First Name: Daisy Last Name: Das Salary: 5000 First Name: John Last Name: Paul Salary: 10000 First Name: Zara Last Name: Ali Salary: 5000

(40)

33

First Name: John Last Name: Paul Salary: 10000

If you check your EMPLOYEE table, it should have the following records:

mysql> select * from EMPLOYEE;

+----+---+---+---+ | id | first_name | last_name | salary | +----+---+---+---+ | 29 | Zara | Ali | 5000 | | 31 | John | Paul | 10000 | +----+---+---+---+ 2 rows in set (0.00 sec

(41)

34 So far, we have seen very basic O/R mapping using hibernate, but there are three most important mapping topics, which we have to learn in detail.

These are:

 Mapping of collections,

 Mapping of associations between entity classes, and  Component Mappings.

Collections Mappings

If an entity or class has collection of values for a particular variable, then we can map those values using any one of the collection interfaces available in java. Hibernate can persist instances of java.util.Map, java.util.Set, java.util.SortedMap, java.util.SortedSet, java.util.List, and any array of persistent entities or values.

Collection type Mapping and Description

java.util.Set This is mapped with a <set> element and initialized with java.util.HashSet

java.util.SortedSet This is mapped with a <set> element and initialized with java.util.TreeSet. The sort attribute can be set to either a comparator or natural ordering.

java.util.List This is mapped with a <list> element and initialized with java.util.ArrayList

java.util.Collection This is mapped with a <bag> or <ibag> element and initialized with java.util.ArrayList

java.util.Map This is mapped with a <map> element and initialized with java.util.HashMap

java.util.SortedMap

This is mapped with a <map> element and initialized with java.util.TreeMap. The sort attribute can be set to either a comparator or natural ordering.

Arrays are supported by Hibernate with <primitive-array> for Java primitive value types and <array> for everything else. However, they are rarely used, so I am not going to discuss them in this tutorial.

If you want to map a user defined collection interfaces, which is not directly supported by Hibernate, you need to tell Hibernate about the semantics of your custom collections, which is not very easy and not recommend to be used.

(42)

35

Hibernate – Set Mappings

A Set is a java collection that does not contain any duplicate element. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most, one null element. So, objects to be added to a set must implement both the equals() and hashCode() methods so that Java can determine whether any two elements/objects are identical.

A Set is mapped with a <set> element in the mapping table and initialized with java.util.HashSet. You can use Set collection in your class when there is no duplicate element required in the collection.

Define RDBMS Tables

Consider a situation where we need to store our employee records in EMPLOYEE table, which would have the following structure:

create table EMPLOYEE (

id INT NOT NULL auto_increment, first_name VARCHAR(20) default NULL, last_name VARCHAR(20) default NULL, salary INT default NULL,

PRIMARY KEY (id) );

Further, assume each employee can have one or more certificate associated with him/her. So, we will store certificate related information in a separate table having the following structure:

create table CERTIFICATE (

id INT NOT NULL auto_increment,

certificate_name VARCHAR(30) default NULL, employee_id INT default NULL,

PRIMARY KEY (id) );

There will be one-to-many relationship between EMPLOYEE and CERTIFICATE objects:

Define POJO Classes

Let us implement our POJO class Employee, which will be used to persist the objects related to EMPLOYEE table and having a collection of certificates in Set variable.

(43)

36

import java.util.*; public class Employee { private int id;

private String firstName; private String lastName; private int salary;

private Set certificates; public Employee() {}

public Employee(String fname, String lname, int salary) { this.firstName = fname;

this.lastName = lname; this.salary = salary; }

public int getId() { return id;

}

public void setId( int id ) { this.id = id;

}

public String getFirstName() { return firstName;

}

public void setFirstName( String first_name ) { this.firstName = first_name;

}

public String getLastName() { return lastName;

}

public void setLastName( String last_name ) { this.lastName = last_name;

}

public int getSalary() { return salary;

(44)

37

}

public void setSalary( int salary ) { this.salary = salary;

}

public Set getCertificates() { return certificates;

}

public void setCertificates( Set certificates ) { this.certificates = certificates;

} }

Now let us define another POJO class corresponding to CERTIFICATE table so that certificate objects can be stored and retrieved into the CERTIFICATE table. This class should also implement both the equals() and hashCode() methods so that Java can determine whether any two elements/objects are identical.

public class Certificate { private int id;

private String name; public Certificate() {}

public Certificate(String name) { this.name = name;

}

public int getId() { return id;

}

public void setId( int id ) { this.id = id;

}

public String getName() { return name;

}

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

(45)

38

public boolean equals(Object obj) { if (obj == null) return false;

if (!this.getClass().equals(obj.getClass())) return false; Certificate obj2 = (Certificate)obj;

if((this.id == obj2.getId()) && (this.name.equals(obj2.getName()))) {

return true; }

return false; }

public int hashCode() { int tmp = 0;

tmp = ( id + name ).hashCode(); return tmp;

} }

Define Hibernate Mapping File

Let us develop our mapping file, which instructs Hibernate how to map the defined classes to the database tables. The <set> element will be used to define the rule for Set collection used.

<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"

"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping>

<class name="Employee" table="EMPLOYEE"> <meta attribute="class-description">

This class contains the employee detail. </meta>

<id name="id" type="int" column="id"> <generator class="native"/>

(46)

39

<set name="certificates" cascade="all"> <key column="employee_id"/>

<one-to-many class="Certificate"/> </set>

<property name="firstName" column="first_name" type="string"/> <property name="lastName" column="last_name" type="string"/> <property name="salary" column="salary" type="int"/>

</class>

<class name="Certificate" table="CERTIFICATE"> <meta attribute="class-description">

This class contains the certificate records. </meta>

<id name="id" type="int" column="id"> <generator class="native"/>

</id>

<property name="name" column="certificate_name" type="string"/> </class>

</hibernate-mapping>

You should save the mapping document in a file with the format <classname>.hbm.xml. We saved our mapping document in the file Employee.hbm.xml. You are already familiar with most of the mapping detail, but let us see all the elements of mapping file once again:  The mapping document is an XML document having <hibernate-mapping> as the root element, which contains two <class> elements corresponding to each class.

 The <class> elements are used to define specific mappings from a Java classes to the database tables. The Java class name is specified using the name attribute of the class element and the database table name is specified using the table attribute.

 The <meta> element is optional element and can be used to create the class description.

 The <id> element maps the unique ID attribute in class to the primary key of the database table. The name attribute of the id element refers to the property in the class and the column attribute refers to the column in the database table. The type attribute holds the hibernate mapping type, this mapping types will convert from Java to SQL data type.

 The <generator> element within the id element is used to generate the primary key values automatically. The class attribute of the generator element is set to

(47)

40 native to let hibernate pick up either identity, sequence or hilo algorithm to create primary key depending upon the capabilities of the underlying database.  The <property> element is used to map a Java class property to a column in the

database table. The name attribute of the element refers to the property in the class and the column attribute refers to the column in the database table. The type attribute holds the hibernate mapping type, this mapping types will convert from Java to SQL data type.

 The <set> element is new here and has been introduced to set the relationship between Certificate and Employee classes. We used the cascade attribute in the <set> element to tell Hibernate to persist the Certificate objects at the same time as the Employee objects. The name attribute is set to the defined Set variable in the parent class, in our case, it is certificates. For each set variable, we need to define a separate set element in the mapping file.

 The <key> element is the column in the CERTIFICATE table that holds the foreign key to the parent object i.e. table EMPLOYEE.

 The <one-to-many> element indicates that one Employee object relates to many Certificate objects and, as such, the Certificate object must have an Employee parent associated with it. You can use either <one-to-one>, <many-to-one> or <many-to-many> elements based on your requirement.

Create Application Class

Finally, we will create our application class with the main() method to run the application. We will use this application to save few Employees’ records along with their certificates and then we will apply CRUD operations on those records.

import java.util.*; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class ManageEmployee {

private static SessionFactory factory; public static void main(String[] args) { try{

factory = new Configuration().configure().buildSessionFactory(); }catch (Throwable ex) {

System.err.println("Failed to create sessionFactory object." + ex); throw new ExceptionInInitializerError(ex);

(48)

41

}

ManageEmployee ME = new ManageEmployee();

/* Let us have a set of certificates for the first employee */ HashSet set1 = new HashSet();

set1.add(new Certificate("MCA")); set1.add(new Certificate("MBA")); set1.add(new Certificate("PMP"));

/* Add employee records in the database */

Integer empID1 = ME.addEmployee("Manoj", "Kumar", 4000, set1); /* Another set of certificates for the second employee */ HashSet set2 = new HashSet();

set2.add(new Certificate("BCA")); set2.add(new Certificate("BA"));

/* Add another employee record in the database */

Integer empID2 = ME.addEmployee("Dilip", "Kumar", 3000, set2); /* List down all the employees */

ME.listEmployees();

/* Update employee's salary records */ ME.updateEmployee(empID1, 5000);

/* Delete an employee from the database */ ME.deleteEmployee(empID2);

/* List down all the employees */ ME.listEmployees();

}

/* Method to add an employee record in the database */ public Integer addEmployee(String fname, String lname,

(49)

42

int salary, Set cert){ Session session = factory.openSession();

Transaction tx = null; Integer employeeID = null; try{

tx = session.beginTransaction();

Employee employee = new Employee(fname, lname, salary); employee.setCertificates(cert);

employeeID = (Integer) session.save(employee); tx.commit(); }catch (HibernateException e) { if (tx!=null) tx.rollback(); e.printStackTrace(); }finally { session.close(); } return employeeID; }

/* Method to list all the employees detail */ public void listEmployees( ){

Session session = factory.openSession(); Transaction tx = null;

try{

tx = session.beginTransaction();

List employees = session.createQuery("FROM Employee").list(); for (Iterator iterator1 =

employees.iterator(); iterator1.hasNext();){ Employee employee = (Employee) iterator1.next();

System.out.print("First Name: " + employee.getFirstName()); System.out.print(" Last Name: " + employee.getLastName()); System.out.println(" Salary: " + employee.getSalary()); Set certificates = employee.getCertificates();

for (Iterator iterator2 =

(50)

43

Certificate certName = (Certificate) iterator2.next(); System.out.println("Certificate: " + certName.getName()); } } tx.commit(); }catch (HibernateException e) { if (tx!=null) tx.rollback(); e.printStackTrace(); }finally { session.close(); } }

/* Method to update salary for an employee */

public void updateEmployee(Integer EmployeeID, int salary ){ Session session = factory.openSession();

Transaction tx = null; try{ tx = session.beginTransaction(); Employee employee = (Employee)session.get(Employee.class, EmployeeID); employee.setSalary( salary ); session.update(employee); tx.commit(); }catch (HibernateException e) { if (tx!=null) tx.rollback(); e.printStackTrace(); }finally { session.close(); } }

/* Method to delete an employee from the records */ public void deleteEmployee(Integer EmployeeID){ Session session = factory.openSession(); Transaction tx = null;

(51)

44 tx = session.beginTransaction(); Employee employee = (Employee)session.get(Employee.class, EmployeeID); session.delete(employee); tx.commit(); }catch (HibernateException e) { if (tx!=null) tx.rollback(); e.printStackTrace(); }finally { session.close(); } } }

Compilation and Execution

Here are the steps to compile and run the above application. Make sure you have set PATH and CLASSPATH appropriately before proceeding for the compilation and execution.

 Create hibernate.cfg.xml configuration file as explained in configuration chapter.  Create Employee.hbm.xml mapping file as shown above.

 Create Employee.java source file as shown above and compile it.  Create Certificate.java source file as shown above and compile it.

 Create ManageEmployee.java source file as shown above and compile it.  Execute ManageEmployee binary to run the program.

You would get the following result on the screen, and at the same time, records would be created in EMPLOYEE and CERTIFICATE tables.

$java ManageEmployee

...VARIOUS LOG MESSAGES WILL DISPLAY HERE... First Name: Manoj Last Name: Kumar Salary: 4000 Certificate: MBA

Certificate: PMP Certificate: MCA

First Name: Dilip Last Name: Kumar Salary: 3000 Certificate: BCA

(52)

45

Certificate: BA

First Name: Manoj Last Name: Kumar Salary: 5000 Certificate: MBA

Certificate: PMP Certificate: MCA

If you check your EMPLOYEE and CERTIFICATE tables, they should have the following records:

mysql> select * from employee;

+----+---+---+---+ | id | first_name | last_name | salary | +----+---+---+---+ | 1 | Manoj | Kumar | 5000 | +----+---+---+---+ 1 row in set (0.00 sec)

mysql> select * from certificate; +----+---+---+ | id | certificate_name | employee_id | +----+---+---+ | 1 | MBA | 1 | | 2 | PMP | 1 | | 3 | MCA | 1 | +----+---+---+ 3 rows in set (0.00 sec)

mysql>

Hibernate – SortedSet Mappings

A SortedSet is a java collection that does not contain any duplicate element and elements are ordered using their natural ordering or by a comparator provided.

A SortedSet is mapped with a <set> element in the mapping table and initialized with java.util.TreeSet. The sort attribute can be set to either a comparator or natural ordering. If we use natural ordering, then its iterator will traverse the set in ascending element order.

(53)

46

Define RDBMS Tables

Consider a situation where we need to store our employee records in the EMPLOYEE table, which will have the following structure:

create table EMPLOYEE (

id INT NOT NULL auto_increment, first_name VARCHAR(20) default NULL, last_name VARCHAR(20) default NULL, salary INT default NULL,

PRIMARY KEY (id) );

Further, assume each employee can have one or more certificate associated with him/her. So, we will store certificate related information in a separate table having the following structure:

create table CERTIFICATE (

id INT NOT NULL auto_increment,

certificate_name VARCHAR(30) default NULL, employee_id INT default NULL,

PRIMARY KEY (id) );

There will be one-to-many relationship between EMPLOYEE and CERTIFICATE objects:

Define POJO Classes

Let us implement our POJO class Employee, which will be used to persist the objects related to EMPLOYEE table and having a collection of certificates in SortedSet variable.

import java.util.*; public class Employee { private int id;

private String firstName; private String lastName; private int salary;

private SortedSet certificates; public Employee() {}

References

Related documents

Star scientist authorships of articles as or with employees of a firm were a potent predictor of the eventual success of biotech firms and Zucker, Darby, and Armstrong (2002)

It shall be the duty of the Commission to eliminate practices having adverse effect on competition, promote and sustain competition, protect the interests of

Below, we address our first two research questions – the overall approach(es) in local and national coverage of white people calling 911 on black individuals and the use of

Reach is a free Total Market Coverage (TMC) product available through Home Delivery or the Mail on Sunday, Monday or Tuesday.. Evening Edge is a free Select Market Coverage

As concerns have been expressed that some landlords might try to interfere in the leaseholders’ right to exercise the RTM, the landlord will not be entitled to be a

Our heuristic algorithm uses k-mean graph clustering to partition the network geographically and another heuristic for the boundary nodes to negotiate their

Effect of mechanical denaturation on surface free energy of protein powdersb. Mohammad Amin Mohammad a,b* ,

It is an open question whether for more than two agents with either additive, or separable and responsive preferences, efficient, individually rational, and weakly transfer- proof