Create a new web project.
So let's start.
Press Ctrl+n (or Strg+n) to open the ?New ...? dialog.
Create a Web Project and select the project name shown below.

Add the Hibernate capabilities by right clicking on the project in the Package View.

Check the two checkboxes to add the libraries to the project and select to create a new hibernate mapping file. The hibernate file holds the configuration of your hibernate settings and mappings.

The next step is to select a Connection Profile for the Database.
Select the button ?New profile? to create a new profile.
When the Postgre Driver is missing. Click on ?New Driver? to create a new driver. You will need the jar including your Database Driver.
We call our profile library-web. Specify the user name and the password and create it.

Back to the first dialog, make sure that you have the checkbox ?Copy JDBC Driver ...? selected. We are going to use PostgreSQL. It should not be difficult to make the same thing for MySQL or another database. Make sure that you have the Jar File of the Database Driver somewhere on your disc. In the source code you will find also a configuration for MySQL.

In the next step you must invent a nice name for your SessionFactory.

What is a SessionFactory?
A session factory creates a Hibernate session for you, so it does what a factory does normally do ;-).
Hibernate expects that only one instance of the Hibernate Session Class is used per thread. Normally you would have to create a class implementing a ThreadLocal pattern. MyEclipse does this for you. Your only have the difficult part to invent a name for it. If you are not using MyEclipse have a look in the sources we provided.
Preparing the project for anybody
MyEclipse provides functionality to create and deploy web projects to a wide choice of application server. Create a web project as explained in the Struts free tools tutorial, we mentioned at the beginning.
What the wizards did is to add all the libraries used by Hibernate, create the hibernate configuration file and create a SessionFactory. You can do this easily by hand.
Download Hibernate from http://www.hibernate.org/
As minimum requirement add the following libraries to get Hibernate 3 to work. When you want to know more about the libraries and if they are required, have a look at the file README.txt included in the lib directory of the hibernate.zip.

The configuration file is a simple XML file named hibernate.cfg.xml
In our case we will put it directly in the src directory. Create an XML file there and add the following content. In the source code you can find the configuration for a MySQL database, I use PostgreSQL here.
<?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>
<session-factory>
<property name="connection.url">jdbc:postgresql://localhost/libraryweb</property>
<property name="connection.username">postgres</property>
<property name="connection.password">p</property>
<property name="connection.driver_class">org.postgresql.Driver</property>
<property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>
</session-factory>
</hibernate-configuration>
Then create the HibernateSessionFactory class in the package de.laliluna.library and add the content as included in the sources with this tutorial.
That's all for the non MyEclipse users.
Reduce Hibernate Libraries
By default MyEclipse includes a heavy load of libraries. Some of them will only be needed for local development others only for special cache implementations. When you want to optimize your deployment after you learned the basics of Hibernate download Hibernate from the website http://www.hibernate.org/ In the lib directory you will find a README.txt explaining what libraries are optional.
Now we are prepared to start the development. Fasten the seatbelts, it is getting really fast now.
Create the Database
Create the database and the following tables. Do not forget the foreign key!
Postgre SQL Script
CREATE TABLE customer
(
id serial NOT NULL,
firstname text,
lastname text,
age int4,
CONSTRAINT customer_pk PRIMARY KEY (id)
) ;
CREATE TABLE book
(
id serial NOT NULL,
title text,
author text,
customer_fk int4,
borrowallowed bool NOT NULL DEFAULT true,
CONSTRAINT book_pk PRIMARY KEY (id)
) ;
ALTER TABLE book
ADD CONSTRAINT book_customer FOREIGN KEY (customer_fk) REFERENCES customer (id) ON UPDATE RESTRICT ON DELETE RESTRICT;
MySQL Script
CREATE TABLE customer
(
id int( 11 ) NOT NULL AUTO_INCREMENT ,
firstname varchar( 255 ) ,
lastname varchar( 255 ) ,
age int( 11 ),
CONSTRAINT customer_pk PRIMARY KEY (id)
) TYPE=INNODB;
CREATE TABLE book( id int( 11 ) NOT NULL AUTO_INCREMENT ,
title varchar( 255 ) ,
author varchar( 255 ) ,
customer_fk int( 11 ),
borrowallowed TINYINT NOT NULL,
CONSTRAINT book_pk PRIMARY KEY ( id ),
INDEX (customer_fk) ) TYPE=INNODB;
ALTER TABLE book ADD CONSTRAINT book_customer FOREIGN KEY ( customer_fk ) REFERENCES customer( id ) ON UPDATE RESTRICT ON DELETE RESTRICT ;
Generate the Hibernate Mapping Files and Classes
Import using MyEclipse
Non MyEclipse user
We will import the tables using MyEclipse to generate the raw mappings. You may use the Hibernate tools to do the same thing. You can find all mappings below.
Open the View DB Browser (MyEclipse). If you cannot find it open the ?Show View? Dialog and select in the MyEclipse Enterprise Workbench the DB Browser.

Open the connection profile you specified before.

Select the two tables we have just created. Right click and choose ?Create Hibernate Mapping?.

Select your LibraryWeb project as target. When your are using PostgreSQL select ?sequence? as ID Generator. When you are using MySQL select ?increment?.

Click OK and your are really good! You have just created your persistence layer ;-)
Now we will have a closer look at our package explorer to see what happened.
First open the hibernate.cfg.xml.
There are two new entries, specifying where the two mapping files are located. It is a good idea to keep the mapping files separated from the hibernate.cfg.xml. (What MyEclipse actually does for you.)
<!-- mapping files -->
<mapping resource="de/laliluna/library/Book.hbm.xml"/>
<mapping resource="de/laliluna/library/Customer.hbm.xml"/>
Have a look at the mapping file Book.hbm.xml. In this file the mapping from the class and its attributes to the table fields is specified. Your foreign key may or may not have been generated. This function is relative new and not working on all platforms.
<?xml version="1.0" encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping package="de.laliluna.library">
<class name="Book" table="book">
<id name="id" column="id" type="java.lang.Integer">
<generator class="sequence"/>
</id>
<property name="title" column="title" type="java.lang.String" />
<property name="author" column="author" type="java.lang.String" />
<property name="customerFk" column="customer_fk" type="java.lang.Integer" />
<property name="borrowallowed" column="borrowallowed" type="java.lang.Byte" />
</class>
</hibernate-mapping>
When you are using MySQL the mapping is slightly different.
<class name="Book" table="book">
<id name="id" column="id" type="java.lang.Integer">
<generator class="increment"/>
</id>
...
MyEclipse created two files per class. The first one is an abstract class. (AbstractBook) It will be overwritten each time you repeat the import procedure. In the second class (Book) you may adapt any changes you want to make. It is only generated once.
Notice
Non MyEclipse users please take the files Book.hbm.xml, AbstractBook, Book, customer.hbm.xml, AbstractCustomer and Customer from the sources provided with this tutorial.
Hibernate does also provide tools to create mapping files. Have a look at the hibernate website.
Improve the mapping of customer
We are going to make some changes.
Hibernate do not generate a relation back from the customer to the book. We will add this by hand.
In the file Customer.class add the following.
private Set books;
return customer;
}
public Set getBooks() {
return books;
}
public void setBooks(Set books) {
this.books = books;
}
In the file Customer.hbm.xml we have to add the mapping from the books variable. Add the set entry to the file.
<?xml version="1.0" encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping package="de.laliluna.library">
<class name="Customer" table="customer">
<id name="id" column="id" type="java.lang.Integer">
<generator class="sequence">
<param name="sequence">customer_id_seq</param>
</generator>
</id>
<set name="books" inverse="false" >
<key>
<column name="customer_fk"></column>
</key>
<one-to-many class="Book" />
</set>
<property name="firstname" column="firstname" type="java.lang.String" />
<property name="lastname" column="lastname" type="java.lang.String" />
<property name="age" column="age" type="java.lang.Integer" />
</class>
</hibernate-mapping>
<generator class="sequence">
This tag specifies how the id is generated. Using PostgreSQL the sequence customer_id_seq is called. The generator depends on your database. For MySQL you will find the example in the source.
<set name="books" inverse="false" >
<key>
<column name="customer_fk"></column>
</key>
<one-to-many class="Book" />
</set>
We have a set, which is accessed by the name books, i.e. GetBooks and setBooks in the Customer class. The foreign key column is customer_fk and related to the mapping of the class Book.
inverse="false"
This is a little more complex to explain. You can write a relation from two sides.
customer.getBooks().add(book);
or
book.setCustomer(customer);
Very often you only need to set the relation from one side. So you can inform Hibernate that it needs not to monitor the offer side of the relation. This could be a performance issue. In this case we would set inverse=?true? and could only use the second approach to write a relation.
When you must use inverse=?true??
Imagine a 1:n relation author to book. A book must have at least one author. The foreign key column author_fk cannot be null opposed to our tutorial example, where the column customer_fk can be null when the book is not borrowed.
When you use not inverse true than there is a possibility that the book is written to the database with the author_fk set to null. In this case you must set the author always on the book side.
book.getAuthors().add(author);
In the class customer I overwrote the toString method to have a proper output during debugging. In addition I changed the constructor method to have the property books initialized with an empty hashset. The advantage is that you do not have to test in the business logic if your hashSet is null or empty.
package de.laliluna.library;
import java.io.Serializable;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* A class that represents a row in the 'customer' table. This class may be
* customized as it is never re-generated after being created.
*/
public class Customer extends AbstractCustomer implements Serializable {
private Set books;
/**
* Simple constructor of Customer instances.
*/
public Customer() {
books = new HashSet();
}
/**
* Constructor of Customer instances given a simple primary key.
*
* @param id
*/
public Customer(java.lang.Integer id) {
super(id);
books = new HashSet();
}
public Set getBooks() {
return books;
}
public void setBooks(Set books) {
this.books = books;
}
/* Add customized code below */
@Override
public String toString() {
return "Customer " + getId() + " firstname: " + getFirstname()
+ " lastname: " + getLastname();
}
}
Improve the mapping of book
See below the content of the Book.hbm.xml file. When you imported this with MyEclipse please correct the borrowAllowed property. The postgre bool column is recognized as Byte and as Short when you are using MySql. Do not ask me why.
<?xml version="1.0" encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping package="de.laliluna.library">
<class name="Book" table="book">
<id name="id" column="id" type="java.lang.Integer">
<generator class="sequence">
<param name="sequence">book_id_seq</param>
</generator>
</id>
<property name="title" column="title" type="java.lang.String" />
<property name="author" column="author" type="java.lang.String" />
<property name="borrowallowed" column="borrowallowed" type="java.lang.Boolean"/>
<many-to-one name="customer" column="customer_fk" not-null="false" >
</many-to-one>
</class>
</hibernate-mapping>
Manually changing the file above is not very good but there is no other way here.
The disadvantage is that this will be overwritten each time you regenerate the mapping files. In our case it is not so important but in a larger project this will make it impossible to use the autogeneration from MyEclipse except at the beginning. The hibernate import function is quite new for MyEclipse, so you can be sure that there will be larger improvements in the next versions.
Notice
I had a problem copy and pasting source code from the tutorial to Eclipse files due to use of tabs in this document. If you encounter funny problems when pasting content to Eclipse, please consider to type the code manually.
Correct the Boolean mapping
Change the variable and the getter and setter in the file AbstractBook.java to Boolean type.
/** The value of the simple borrowallowed property. */
private java.lang.Boolean borrowallowed;
/**
* Return the value of the borrowallowed column.
* @return java.lang.Byte
*/
public java.lang.Boolean getBorrowallowed()
{
return this.borrowallowed;
}
/**
* Set the value of the borrowallowed column.
* @param borrowallowed
*/
public void setBorrowallowed(java.lang.Boolean borrowallowed)
{
this.borrowallowed = borrowallowed;
}
In the class Book I overwrote the toString method to get a proper output during debugging. If the relation to customer is not detected properly, here is the complete code of the class.
package de.laliluna.library;
import java.io.Serializable;
/**
* A class that represents a row in the 'book' table.
* This class may be customized as it is never re-generated
* after being created.
*/
public class Book
extends AbstractBook
implements Serializable
{
private Customer customer;
@Override
public String toString() {
return "Book: " + getId()+" title: "+getTitle()+" author: "+getAuthor() + " borrowed to: "+getCustomer();
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
/**
* Simple constructor of Book instances.
*/
public Book()
{
}
/**
* Constructor of Book instances given a simple primary key.
* @param id
*/
public Book(java.lang.Integer id)
{
super(id);
}
/* Add customized code below */
}
Improvements to the session factory
The session factory generated by MyEclipse is not very nice because it lets you run into errors when you use the session.close() method. The session factory expects that you use the static method closeSession() of the factory, which actually sets the session to null if it is closed.
But no problem, here are the changes to the method currentSession of the factory.
public static Session currentSession() throws HibernateException {
Session session = (Session) threadLocal.get();
/*
* [laliluna] 20.12.2004
* we want to use the standard session.close() method and not the closeSession() from this class.
* For this we need the following line of code.
*/
if (session != null && !session.isOpen()) session = null;
if (session == null) {
if (sessionFactory == null) {
try {
cfg.configure(CONFIG_FILE_LOCATION);
sessionFactory = cfg.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating HibernateSessionFactory %%%%");
e.printStackTrace();
}
}
session = sessionFactory.openSession();
threadLocal.set(session);
}
return session;
}Testing the Hibernate part
We will need log4j to test Hibernate outside of an Application Server. You can find the library as jar file here:
http://logging.apache.org/
Add the library to your Eclipse project (project properties => Java Build Path => Add Jar or Add external Jar. You can find a basic log4j.properties file in the source.
Create a new class to implement the test methods.

Add the following content:
package de.laliluna.library.test;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.Transaction;
import de.laliluna.library.Book;
import de.laliluna.library.Customer;
import de.laliluna.library.HibernateSessionFactory;
public class LibraryTest {
private Session session;
private Logger log;
public static void main(String[] args) {
/*
* hibernate needs log4j. Either create a log4j.properties file in the
* source directory * or alternatively make the following to create a
* standard configuration BasicConfigurator.configure();
*/
LibraryTest libraryTest = new LibraryTest();
try {
libraryTest.setUp();
libraryTest.testCreateDomains();
libraryTest.testAddRemoveRelation();
libraryTest.listBooks();
libraryTest.tearDown();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void testCreateDomains() {
Transaction tx = session.beginTransaction();
Book book = new Book();
book.setAuthor("Sebastian");
book.setTitle("Hibernation in winter");
book.setBorrowallowed(true);
session.save(book);
tx.commit();
tx = session.beginTransaction();
Customer customer = new Customer();
customer.setLastname("Liebzeit");
customer.setFirstname("Carsten");
customer.setAge(25);
session.save(customer);
tx.commit();
}
private void testAddRemoveRelation() {
log.info("Adding and removing relations");
Transaction tx = session.beginTransaction();
// create two books and a customer
Book book = new Book();
book.setAuthor("Sebastian's");
book.setTitle("Hibernation in the summer");
book.setBorrowallowed(true);
session.save(book);
Book book2 = new Book();
book2.setAuthor("Karl May");
book2.setTitle("Wildes Kurdistan");
book2.setBorrowallowed(true);
session.save(book2);
Customer customer = new Customer();
customer.setLastname("Meier");
customer.setFirstname("John");
customer.setAge(25);
session.save(customer);
//customer borrows books
customer.getBooks().add(book);
customer.getBooks().add(book2);
session.flush();
session.refresh(customer);
session.refresh(book);
session.refresh(book2);
Set books = customer.getBooks();
log.info("list books of customer");
for (Iterator iter = books.iterator(); iter.hasNext();) {
Book element = (Book) iter.next();
log.info(element);
}
//first book is returned
book.setCustomer(null);
customer.getBooks().remove(book);
session.flush();
session.refresh(customer);
log.info("list books of customer");
books = customer.getBooks();
for (Iterator iter = books.iterator(); iter.hasNext();) {
Book element = (Book) iter.next();
log.info(element);
}
tx.commit();
tx = session.beginTransaction();
session.delete(customer);
session.delete(book);
session.delete(book2);
tx.commit();
}
protected void setUp() throws Exception {
session = HibernateSessionFactory.currentSession();
log = Logger.getLogger(this.getClass());
}
protected void tearDown() throws Exception {
HibernateSessionFactory.closeSession();
}
/**
* creates a book and saves it to the db.
*
*/
/**
* lists all books in the db
*
*/
private void listBooks() {
log.info("####### list customers");
Transaction tx = session.beginTransaction();
List customers = session.createQuery("select c from Customer as c")
.list();
for (Iterator iter = customers.iterator(); iter.hasNext();) {
Customer element = (Customer) iter.next();
Set books = element.getBooks();
System.out.println(element);
if (books == null)
log.info("no books");
else {
for (Iterator iterator = books.iterator(); iterator.hasNext();) {
Book book = (Book) iterator.next();
log.info(" - " + book);
}
}
log.info(element);
}
tx.commit();
log.info("####### list books");
tx = session.beginTransaction();
List books = session.createQuery("select b from Book as b").list();
for (Iterator iter = books.iterator(); iter.hasNext();) {
System.out.println((Book) iter.next());
}
tx.commit();
}
/**
* @return Returns the session.
*/
public Session getSession() {
return session;
}
/**
* @param session
* The session to set.
*/
public void setSession(Session session) {
this.session = session;
}
}
Right click on the class and choose Run -> Java Application.

And at least when we are using PostgreSQL, we got a lots of error message. ;-)
java.sql.SQLException: ERROR: relation "hibernate_sequence" does not exist
PostgreSQL Problem
This is because there is a simple bug in the import script. It assumes that the sequence is called hibernate_sequence. The sequences created automatically when your are using a serial column, is called table_column_seq, eg: book_id_seq.
The easiest work around is to wait until MyEclipse improves the script. The fastest to create a sequence called hibernate_sequence. A disadvantage is that all tables share the same sequence.
CREATE SEQUENCE hibernate_sequence
INCREMENT 1
MINVALUE 1
MAXVALUE 9223372036854775807
START 1
CACHE 1;
The nicest way, but only possible when you are sure not to regenerate your mapping files (you would override your changes) is to change the mapping from
<generator class="sequence"/>
to the following for the book. The changes for the customer are analogues.
<generator class="sequence">
<param name="sequence">book_id_seq</param>
</generator>
That's it for the persistence layer for our application.
Generating the Business Logic
Create a business logic class
We will place all business logic in a single class. Later our Struts part will only use this Class. There won't be any direct access to the persistence layer. You could even think about replacing your persistence layer with another one.

This class will hold all methods we need as business logic
creating, updating and deleting books
creating, updating and deleting customers
borrowing and returning books
reading all customers or books from the db into a list
Hibernate Design we used
A hibernate query returns a List interface to a special Hibernate implementation of a List. This implementation is directly connected to the session. You cannot close your session when you use this Hibernate lists. Either you have to disconnect the session from the database and reconnect it, use one of the caching solutions or take the easiest but not best way to work with Value Objects.
We took the easiest way:
The consequence is that we have to copy all elements of a hibernate list to a normal java.util.List.
/*
* Created on 25.11.2004 by HS
*
*/
package de.laliluna.library.bl;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.hibernate.Session;
import org.hibernate.Transaction;
import de.laliluna.library.Book;
import de.laliluna.library.Customer;
import de.laliluna.library.HibernateSessionFactory;
/**
* @author HS
*
*
*/
public class LibraryManager {
/**
* get all books from the database
*
* @return Array of BookValue
*/
public Book[] getAllBooks() {
/* will hold the books we are going to return later */
List books = new ArrayList();
/* a Hibernate session */
Session session = null;
/* we always need a transaction */
Transaction tx = null;
/* get session of the current thread */
session = HibernateSessionFactory.currentSession();
tx = session.beginTransaction();
List tmpBooks = session.createQuery(
"select b from Book as b order by b.author, b.title").list();
for (Iterator iter = tmpBooks.iterator(); iter.hasNext();) {
books.add((Book) iter.next());
}
tx.commit();
return (Book[]) books.toArray(new Book[0]);
}
/**
* get book by primary key
*
* @param primaryKey
* @return a Book or null
*/
public Book getBookByPrimaryKey(Integer primaryKey) {
/* holds our return value */
Book book = null;
/* a Hibernate session */
Session session = null;
/* we always need a transaction */
Transaction tx = null;
/* get session of the current thread */
session = HibernateSessionFactory.currentSession();
tx = session.beginTransaction();
book = (Book) session.get(Book.class, primaryKey);
tx.commit();
return book;
}
/**
* sets the book as borrowed to the user specified in the database
*
* @param primaryKey
* @param userPrimaryKey
*/
public void borrowBook(Integer primaryKey, Integer customerPrimaryKey) {
/* a Hibernate session */
Session session = null;
/* we always need a transaction */
Transaction tx = null;
/* get session of the current thread */
session = HibernateSessionFactory.currentSession();
tx = session.beginTransaction();
Book book = (Book) session.get(Book.class, primaryKey);
// only if borrowing of the book is allowed
if (book.getBorrowallowed()) {
Customer customer = (Customer) session.get(Customer.class,
customerPrimaryKey);
if (book != null && customer != null)
book.setCustomer(customer);
}
tx.commit();
}
/**
* customer returns a book, relation in the db between customer and book is
* deleted
*
* @param primaryKey
*/
public void returnBook(Integer primaryKey) {
/* a Hibernate session */
Session session = null;
/* we always need a transaction */
Transaction tx = null;
/* get session of the current thread */
session = HibernateSessionFactory.currentSession();
tx = session.beginTransaction();
Book book = (Book) session.get(Book.class, primaryKey);
if (book != null) {
// session.get returns null when no entry is found
Customer customer = book.getCustomer();
if (customer != null) {
customer.getBooks().remove(book);
book.setCustomer(null);
}
}
tx.commit();
}
/**
* updates/creates a book
*
* @param bookValue
*/
public void saveBook(Book bookValue) {
/* a Hibernate session */
Session session = null;
/* we always need a transaction */
Transaction tx = null;
/* get session of the current thread */
session = HibernateSessionFactory.currentSession();
tx = session.beginTransaction();
Book book;
if (bookValue.getId() != null && bookValue.getId().intValue() != 0) { // [laliluna]
// 04.12.2004
// load
// book
// from
// DB
book = (Book) session.get(Book.class, bookValue.getId());
if (book != null) {
book.setAuthor(bookValue.getAuthor());
book.setTitle(bookValue.getTitle());
book.setBorrowallowed(bookValue.getBorrowallowed());
session.update(book);
}
} else // [laliluna] 04.12.2004 create new book
{
book = new Book();
book.setAuthor(bookValue.getAuthor());
book.setTitle(bookValue.getTitle());
book.setBorrowallowed(bookValue.getBorrowallowed());
session.save(book);
}
tx.commit();
}
/**
* deletes a book
*
* @param primaryKey
*/
public void removeBookByPrimaryKey(Integer primaryKey) {
/* a Hibernate session */
Session session = null;
/* we always need a transaction */
Transaction tx = null;
/* get session of the current thread */
session = HibernateSessionFactory.currentSession();
tx = session.beginTransaction();
Book book = (Book) session.get(Book.class, primaryKey);
if (book != null)
if (book.getCustomer() != null)
book.getCustomer().getBooks().remove(book);
session.delete(book);
tx.commit();
}
/**
* returns all customers from the db
*
* @return
*/
public Customer[] getAllCustomers() {
/* will hold the books we are going to return later */
List customers = new ArrayList();
/* a Hibernate session */
Session session = null;
/* we always need a transaction */
Transaction tx = null;
/* get session of the current thread */
session = HibernateSessionFactory.currentSession();
tx = session.beginTransaction();
List tmpCustomer = session.createQuery(
"select c from Customer as c order by c.lastname").list();
for (Iterator iter = tmpCustomer.iterator(); iter.hasNext();) {
customers.add((Customer) iter.next());
}
tx.commit();
return (Customer[]) customers.toArray(new Customer[0]);
}
/**
* gets a customer from the db
*
* @param primaryKey
* @return the customer class or null, when no customer is found
*/
public Customer getCustomerByPrimaryKey(Integer primaryKey) {
/* holds our return value */
Customer customer = null;
/* a Hibernate session */
Session session = null;
/* we always need a transaction */
Transaction tx = null;
/* get session of the current thread */
session = HibernateSessionFactory.currentSession();
tx = session.beginTransaction();
customer = (Customer) session.get(Customer.class, primaryKey);
tx.commit();
return customer;
}
/**
* saves the customers to the db
*
* @param customer
*/
public void saveCustomer(Customer customer) {
/* a Hibernate session */
Session session = null;
/* we always need a transaction */
Transaction tx = null;
/* get session of the current thread */
session = HibernateSessionFactory.currentSession();
tx = session.beginTransaction();
if (customer.getId() == null || customer.getId().intValue() == 0) // [laliluna]
// 06.12.2004
// create
// customer
session.save(customer);
else {
Customer toBeUpdated = (Customer) session.get(Customer.class,
customer.getId());
toBeUpdated.setAge(customer.getAge());
toBeUpdated.setLastname(customer.getLastname());
toBeUpdated.setFirstname(customer.getFirstname());
session.update(toBeUpdated);
}
tx.commit();
}
/**
* deletes a customer from the database
*
* @param primaryKey
*/
public void removeCustomerByPrimaryKey(Integer primaryKey) {
/* a Hibernate session */
Session session = null;
/* we always need a transaction */
Transaction tx = null;
/* get session of the current thread */
session = HibernateSessionFactory.currentSession();
tx = session.beginTransaction();
Customer customer = (Customer) session.get(Customer.class, primaryKey);
if (customer != null) {
Set books = customer.getBooks();
for (Iterator iter = books.iterator(); iter.hasNext();) {
Book element = (Book) iter.next();
element.setCustomer(null);
}
session.delete(customer);
}
tx.commit();
}
}
That's all we have created our business logic.
And now the last part: the dialogs
Creating the dialogs with Struts
For now your project is still a normal Web project, so we need to add the struts capabilityies. Right click on the project and add the capabilityies for struts with Add Struts Capabilityies.

Change the Base package for new classes and the
Default application resource.

Notice
You can use the libraries and tlds found in the struts-blanc.war when you do not have MyEclipse. Download struts from
You can find the struts-blank.war in the folder jakarta-struts-1.2.4/webapps.
Create a default, welcome page
Ok, now we want to create a default page. Right click (yes again) on the Folder WebRoot in the Project and choose New > JSP.
discuss this topic to forum
