Hibernate and Struts with JBuilder and MySQL - by Yuri Marx

By: Yuri Gomes

Abstract: This tutorial is a step-by-step how to use Hibernate, Struts and MySQL with JBuilder

Hibernate and Struts with JBuilder and MySQL

Introduction

Hibernate is a Open-Source Tool used to persist objects in RDBMS (Relational DataBase Management System) systems, as Oracle, SQL Server, DB2, MySQL, Interbase and outhers. It's a ORM (Object Relational Mapping) framework. Thus, is possible creates a class model and maps them to the relational database model.

Download and Install Procedures

Hibernate Install

Hibernate framework is an open-source project located in Sourceforge.net website. To have access to the project it has access the Hibernate Website. Two options of download exist:

  • Download Hibernate Core to get the Hibernate tool.
  • Download Hibernate Annotations to get support to programming with annotations in the Hibernate.
  • Download Hibernate Tools to get tools that facilitate the development with Hibernate
  • Download Hibernate EntityManager to develop Entity Beans 3.0 with Hibernate without EJB Containers.

Open Hibernate Core zip file and unpacks the same where to desire. To install the Hibernate in JBuilder do it:

  1. Open JBuilder.
  2. Go to the Tools > Configure > Libraries...
  3. Press New... button.
  4. Set Name field with "Hibernate" value.
  5. Set Location field with "User Home" value.
  6. Press Add... button.
  7. Go to the hibernate directory (where the zip archive was unpacked), select hibernate3.jar and press Ok button.
  8. Press Add... button again and go to the lib directory in the hibernate directory and select all .jars files.
  9. Click Ok button to finalize the framework install.
  10. Click Ok to finalize the process.

MySQL Install

MySQL database is an open-source project located in Sourceforge.net website. To have access to the project it has access the MySQL Website. Actually, the MySQL 4.1 is recommend version.

Open file downloaded and install your MySQL.

Download and Install JDBC Driver for MySQL

To access MySQL tables you must have one JDBC driver. It's encountered in MySQL Website in the Download > Connectors > Connector/J link. Download the zip file. After download, open zip file and extract it to the desired directory.

To install the JDBC Driver for MySQL in JBuilder do it:

  1. Open JBuilder.
  2. Go to the Tools > Configure > Libraries...
  3. Press New... button.
  4. Set Name field with "MySQL" value.
  5. Set Location field with "User Home" value.
  6. Press Add... button.
  7. Go to the JDBC driver for MySQL directory (where the zip archive was unpacked), select mysql-connector-java-3.1.10-bin.jar and press Ok button.
  8. Click Ok button to finalize the framework install.

Working with Hibernate

Creating a new Project in JBuilder

This example uses Struts and Hibernate.

  1. Open JBuilder.
  2. Go to in File > New Project... > Set a name to the Project with the "HibernateProject" value > Click in the Next button.
  3. To Config the Hibernate Library Path, Go to the Required Libraries Tab > Click in the Add... button > Select Hibernate and click Ok button.
  4. To Config the MySQL Library Path, Go to the Required Libraries Tab > Click in the Add... button > Select MySQL and click Ok button.
  5. Click in the Finish button.

Creating the Web Module of the Project

In this pass will be created the Web Module of the project.

  1. Go to the File > New...
  2. Choose "Web" section.
  3. Choose "Web Module (WAR)" wizard and click in the Ok button.
  4. Select "Tomcat 5.0" in the combobox and click in the Ok button.
  5. Select "Create empty Web Module" option and click in the Next button.
  6. Set Name field to the "hibernateWAR".
  7. Mantains suggestion to the Directory field.
  8. Select "When building project or module" to the Build Web Archieve field.
  9. In available standards select Servlet 2.4 and JSP 2.0.
  10. Click in the button Next.
  11. Select the Struts 1.1 option.
  12. Click in the Finish button.

Creating the Web Files to the Web Module of the Project

In this pass will be created Struts and JSP components to the project and the Beans that will be persisted in the database.

Creating the Bean

  1. Go to the File > New...
  2. Choose "General" section.
  3. Choose "JavaBean" wizard and click in the Ok button.
  4. Set "Employee" value to the Class Name field.
  5. Mantains suggestions to the Package and Base Class fields.
  6. In the Options only fields checked are "Public" and "Generate default constructor" options. The all others options must be unchecked.
  7. Click in the Ok button. The Employee class was created and your source code appears in the Code Editor.
  8. Go to the "Bean" tab, in the footer of the Code Editor.
  9. Go to the "Properties" tab.
  10. Click in the Add Property... button. Set the values indicated in the below table and click Apply. Create each field presented in the below table and click in Apply. When all field are created click in the Ok button.
Property Name
Type
idEmployee java.lang.Integer
name java.lang.String
age java.lang.Integer
gendre java.lang.String
salary java.lang.Double
the all outhers fields must be mantained as suggested.

Creating the JSP

  1. Go to the File > New...
  2. Choose "Web" section.
  3. Choose "JSP" section.
  4. Choose "hibernateWAR" option to the Web Module field.
  5. Set "employee" value to the Name field.
  6. Mantains unchecked the "Generate sample bean" and "Generate error page" options.
  7. Click in the Next button.
  8. Choose the background color to the Background field.
  9. Mantains checked the "Generate submit form".
  10. In Tag Libraries > Struts 1.1, select all options, "struts-bean", "struts-html", "struts-logic", "struts-template", "struts-tiles" and "struts-nested" options in their checkboxes, all outhers ckeckboxes must be unchecked.
  11. Click in the Next button.
  12. Click in the Add Bean... button.
  13. Select the Bean created before in this article (hibernateproject.Employee class) and click Ok button.
  14. Set ID field in the table to the "employee" value.
  15. Set Scope field in the table to the "request" value.
  16. Click in the Next button.
  17. Mantains checked "Create a runtime configuration".
  18. Maintains the suggestion to the Name field.
  19. Click in the Finish button.
  20. The employee.jsp file was created and now it's appears in the Code Editor.
  21. Delete all HTML code inside <body> tag and includes the follow HTML code, after press ALT+Shift+K to format HTML code:
<form>
<table width="55%" border="1" cellpadding="0" cellspacing="0" bordercolor="#000000">
	<tr bgcolor="#99CCCC">
		<td colspan="5">
			<div align="center">
				<strong>Employee Catalog</strong>
			</div>
			<input name="idEmployee" type="hidden">
		</td>
	</tr>
	<tr bordercolor="#000066" bgcolor="#999999">
		<td colspan="5">
			<font color="#FFFFFF"> </font>
		</td>
	</tr>
	<tr bordercolor="#999999" bgcolor="#999999">
		<td width="17%">
			<div align="right">
				<font color="#FFFFFF">
					<strong>Name:</strong>
				</font>
			</div>
		</td>
		<td colspan="2">
			<font color="#FFFFFF">
				<input name="name" type="text" size="30">
			</font>
		</td>
		<td width="18%">
			<div align="right">
				<font color="#FFFFFF">
					<strong>Age:</strong>
				</font>
			</div>
		</td>
		<td width="23%">
			<font color="#FFFFFF">
				<input name="age" type="text" size="15">
			</font>
		</td>
	</tr>
	<tr bordercolor="#999999" bgcolor="#999999">
		<td>
			<div align="right">
				<font color="#FFFFFF">
					<strong>Gendre:</strong>
				</font>
			</div>
		</td>
		<td colspan="2">
			<font color="#FFFFFF">
				<input name="gendre" type="text" size="20">
			</font>
		</td>
		<td>
			<div align="right">
				<font color="#FFFFFF">
					<strong>Salary:</strong>
				</font>
			</div>
		</td>
		<td>
			<font color="#FFFFFF">
				<input name="salary" type="text" size="10">
			</font>
		</td>
	</tr>
	<tr bordercolor="#000066" bgcolor="#999999">
		<td colspan="5">
			<font color="#FFFFFF"> </font>
		</td>
	</tr>
	<tr bgcolor="#99CCCC">
		<td colspan="5">
			<div align="left">
				<input name="action" type="submit" value="Post">
				<input name="action" type="submit" value="Update">
				<input name="action" type="submit" value="Delete">
				<input name="action" type="submit" value="Find">
			</div>
		</td>
	</tr>
</table>
</form>

Converting HTML Tags to the Struts Tags

In this section will be presented the Struts Converter Wizard.

  1. Go to the File > New...
  2. Choose "Web" section.
  3. Choose "Struts Converter" wizard and Click in the Ok button.
  4. Set Web Module field with "hibernateWAR" value.
  5. Click in the Add Files... button.
  6. Choose employee.jsp file and click Ok button.
  7. Click in the Next button.
  8. Click in the Select All button.
  9. Click in the Next button.
  10. Mantains suggestions in this screen and click in the Finish button.
  11. The jsp file was converted to struts file.
  12. Find <html:form action=""> line in the jsp file. Replace by <html:form action="/employeeAction.do" method="post">.
  13. Save the jsp file.

Creating ActionForm Class

  1. Go to the File > New...
  2. Choose "Web" section.
  3. Choose ActionForm wizard and click in Ok button.
  4. Set ActionForm field with "EmployeeActionForm" value.
  5. Mantains all outhers suggestions and click in the Next button.
  6. Click in the Add from JSP... button.
  7. Select employee.jsp and click in the Ok button.
  8. Alter properties types for correct types (age and idEmployee with java.lang.Integer and salary with java.lang.Double). To Edit the type, select the field, click in the Edit... button, alters type field and click the Ok button. Repeat for each field to be updated.
  9. After edit fields, click in the Next button.
  10. Mantains all suggestions in this screen and click in the Finish button.
  11. The EmployeeActionForm is created and showed in the Struts Config Designer.
  12. Save All files.

Creating Action Class

  1. Go to the File > New...
  2. Choose "Web" section.
  3. Choose Action wizard.
  4. Set Action field with "EmployeeAction" value.
  5. Mantains all outhers suggestions and click in the Next Field.
  6. Set FormBean name field with "employeeActionForm" value.
  7. Set Scope field with "request" value.
  8. Set Validate FormBean with "false" value.
  9. Press "..." button to the Input JSP field, choose employee.jsp file and click in the Ok button. The value of the field will be "/employee.jsp".
  10. Click in the Finish button.
  11. The EmployeeAction Class was created and the Struts Designer appears with the Action associations.
  12. In the Project Pane find employee.jsp (in hibernateWAR > Module Directory > employee.jsp) and drag-in-drop into <forward> icone in the Struts Designer.
  13. Now, the all actions associations are completed.
  14. Save All files.

Creating the Hibernate Classes

In this pass will be created all Hibernate classes, DAO (Data Acess Object) classes and mapping of the classes that must be persisted.

Creating the general Exception Class for Hibernate Errors and Exceptions

This class is used to manipulate exceptions in the Hibernate code.

  1. Go to the File > New...
  2. Choose "General" section.
  3. Choose "Class" wizard and click in the Ok button.
  4. Set Class Name field with "InfrastructureException" value.
  5. Mantains the all outhers values suggestions and click Ok button.
  6. Implement the below source code, format code (Shift+ALT+K) and save all.
package hibernateproject;

/**
 * This exception is used to mark (fatal) failures in infrastructure and system code.
 *
 * @author Christian Bauer <christian@hibernate.org>
 */
public class InfrastructureException extends RuntimeException {

    public InfrastructureException() {
    }

    public InfrastructureException(String message) {
        super(message);
    }

    public InfrastructureException(String message, Throwable cause) {
        super(message, cause);
    }

    public InfrastructureException(Throwable cause) {
        super(cause);
    }
}

Creating the helper class of the Hibernate

This class is used to initiate Hibernate and get access to a session of the persistence and transaction operations.

  1. Go to the File > New...
  2. Choose "General" section.
  3. Choose "Class" wizard and click in the Ok button.
  4. Set Class name field with "HibernateUtil" value.
  5. Mantains the all outhers values suggestions and click Ok button.
  6. Implement the below source code, format code (Shift+ALT+K) and save all.
package hibernateproject;

import org.hibernate.*;
import org.hibernate.cfg.Configuration;
import org.apache.commons.logging.*;

import javax.naming.*;


/**
 * Basic Hibernate helper class, handles SessionFactory, Session and Transaction.
 * <p>
 * Uses a static initializer for the initial SessionFactory creation
 * and holds Session and Transactions in thread local variables. All
 * exceptions are wrapped in an unchecked InfrastructureException.
 *
 * @author christian@hibernate.org
 */
public class HibernateUtil {

    private static Log log = LogFactory.getLog(HibernateUtil.class);

    private static Configuration configuration;
    private static SessionFactory sessionFactory;
    private static final ThreadLocal threadSession = new ThreadLocal();
    private static final ThreadLocal threadTransaction = new ThreadLocal();
    private static final ThreadLocal threadInterceptor = new ThreadLocal();

    // Create the initial SessionFactory from the default configuration files

    static {
        try {
            configuration = new Configuration();
            sessionFactory = configuration.configure().buildSessionFactory();
            // We could also let Hibernate bind it to JNDI:

            // configuration.configure().buildSessionFactory()
        } catch (Throwable ex) {
            // We have to catch Throwable, otherwise we will miss
            // NoClassDefFoundError and other subclasses of Error
            log.error("Building SessionFactory failed.", ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    /**
     * Returns the SessionFactory used for this static class.
     *
     * @return SessionFactory
     */

    public static SessionFactory getSessionFactory() {
        /* Instead of a static variable, use JNDI:
                         SessionFactory sessions = null;
                         try {
                Context ctx = new InitialContext();
                String jndiName = "java:hibernate/HibernateFactory";
                sessions = (SessionFactory)ctx.lookup(jndiName);
                         } catch (NamingException ex) {
                throw new InfrastructureException(ex);
                         }
                         return sessions;
         */
        return sessionFactory;
    }

    /**
     * Returns the original Hibernate configuration.
     *
     * @return Configuration
     */

    public static Configuration getConfiguration() {
        return configuration;
    }

    /**
     * Rebuild the SessionFactory with the static Configuration.
     *
     */
    public static void rebuildSessionFactory() throws InfrastructureException {
        synchronized (sessionFactory) {
            try {
                sessionFactory = getConfiguration().buildSessionFactory();
            } catch (Exception ex) {
                throw new InfrastructureException(ex);
            }
        }
    }

    /**
     * Rebuild the SessionFactory with the given Hibernate Configuration.
     *
     * @param cfg
     */

    public static void rebuildSessionFactory(Configuration cfg) throws
            InfrastructureException {
        synchronized (sessionFactory) {
            try {
                sessionFactory = cfg.buildSessionFactory();
                configuration = cfg;
            } catch (Exception ex) {
                throw new InfrastructureException(ex);
            }
        }
    }

    /**
     * Retrieves the current Session local to the thread.
     * <p/>

     * If no Session is open, opens a new Session for the running thread.
     *
     * @return Session
     */
    public static Session getSession() throws InfrastructureException {
        Session s = (Session) threadSession.get();
        try {
            if (s == null) {
                log.debug("Opening new Session for this thread.");
                if (getInterceptor() != null) {
                    log.debug("Using interceptor: " + getInterceptor().getClass());
                    s = getSessionFactory().openSession(getInterceptor());
                } else {
                    s = getSessionFactory().openSession();
                }
                threadSession.set(s);
            }
        } catch (HibernateException ex) {
            throw new InfrastructureException(ex);
        }
        return s;
    }

    /**
     * Closes the Session local to the thread.
     */

    public static void closeSession() throws InfrastructureException {
        try {
            Session s = (Session) threadSession.get();
            threadSession.set(null);
            if (s != null && s.isOpen()) {
                log.debug("Closing Session of this thread.");
                s.close();
            }
        } catch (HibernateException ex) {
            throw new InfrastructureException(ex);
        }
    }

    /**
     * Start a new database transaction.
     */

    public static void beginTransaction() throws InfrastructureException {
        Transaction tx = (Transaction) threadTransaction.get();
        try {
            if (tx == null) {
                log.debug("Starting new database transaction in this thread.");
                tx = getSession().beginTransaction();
                threadTransaction.set(tx);
            }
        } catch (HibernateException ex) {
            throw new InfrastructureException(ex);
        }
    }

    /**
     * Commit the database transaction.
     */

    public static void commitTransaction() throws InfrastructureException {
        Transaction tx = (Transaction) threadTransaction.get();
        try {
            if (tx != null && !tx.wasCommitted()
                && !tx.wasRolledBack()) {
                log.debug("Committing database transaction of this thread.");
                tx.commit();
            }
            threadTransaction.set(null);
        } catch (HibernateException ex) {
            rollbackTransaction();
            throw new InfrastructureException(ex);
        }
    }

    /**
     * Commit the database transaction.
     */

    public static void rollbackTransaction() throws InfrastructureException {
        Transaction tx = (Transaction) threadTransaction.get();
        try {
            threadTransaction.set(null);
            if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack()) {
                log.debug(
                        "Tyring to rollback database transaction of this thread.");
                tx.rollback();
            }
        } catch (HibernateException ex) {
            throw new InfrastructureException(ex);
        } finally {
            closeSession();
        }
    }

    /**
     * Reconnects a Hibernate Session to the current Thread.
     *
     * @param session The Hibernate Session to be reconnected.
     */

    public static void reconnect(Session session) throws
            InfrastructureException {
        try {
            session.reconnect();
            threadSession.set(session);
        } catch (HibernateException ex) {
            throw new InfrastructureException(ex);
        }
    }

    /**
     * Disconnect and return Session from current Thread.
     *
     * @return Session the disconnected Session
     */

    public static Session disconnectSession() throws InfrastructureException {

        Session session = getSession();
        try {
            threadSession.set(null);
            if (session.isConnected() && session.isOpen()) {
                session.disconnect();
            }
        } catch (HibernateException ex) {
            throw new InfrastructureException(ex);
        }
        return session;
    }

    /**
     * Register a Hibernate interceptor with the current thread.
     * <p>

     * Every Session opened is opened with this interceptor after
     * registration. Has no effect if the current Session of the
     * thread is already open, effective on next close()/getSession().
     */
    public static void registerInterceptor(Interceptor interceptor) {
        threadInterceptor.set(interceptor);
    }

    private static Interceptor getInterceptor() {
        Interceptor interceptor =
                (Interceptor) threadInterceptor.get();
        return interceptor;
    }

}

Creating DAO Class

This DAO class encapsulate all functionaties necessary to persist Employee data in the Database using Hibernate. Thus, the action class will be use responsable by get information from employee, pass to persist for the DAO class and return sucess or error to the user.

  1. Go to File > New...
  2. Choose "General" section.
  3. Choose "Class" wizard and click in the Ok button.
  4. Set "EmployeeDAO" value to the Class name field.
  5. Mantains suggestions to all other fields and click in Ok button.
  6. Implement below souce code, format code (Shift+ALT+K) and save all.
package hibernateproject;

import org.hibernate.*;

import java.util.Collection;
import org.hibernate.criterion.Expression;

/**
 * A typical DAO for categories using Hibernate.
 *
 * @author Christian Bauer <christian@hibernate.org>
 */

public class EmployeeDAO {

    public EmployeeDAO() {
        HibernateUtil.beginTransaction();
    }

    // ********************************************************** //

    public Employee getEmployeeById(Long employeeId, boolean lock) throws

            InfrastructureException {

        Session session = HibernateUtil.getSession();

        Employee employee = null;
        try {
            if (lock) {
                employee = (Employee) session.load(Employee.class, employeeId,
                                                 LockMode.UPGRADE);
            } else {
                employee = (Employee) session.load(Employee.class, employeeId);
            }
        } catch (HibernateException ex) {
            throw new InfrastructureException(ex);
        }
        return employee;
    }

    // ********************************************************** //

    public Collection findAll() throws InfrastructureException {

        Collection employees;
        try {

            employees = HibernateUtil.getSession().createCriteria(Employee.class).
                        list();

        } catch (HibernateException ex) {
            throw new InfrastructureException(ex);
        }
        return employees;
    }

    // ********************************************************** //

    public Collection findByName(String employeeName) throws
            InfrastructureException {

        Collection employees;
        try {
            Criteria crit = HibernateUtil.getSession().createCriteria(Employee.class);
            employees = crit.add(Expression.like("employee", employeeName)).list();
        } catch (HibernateException ex) {
            throw new InfrastructureException(ex);
        }
        return employees;
    }

    // ********************************************************** //

    public void makePersistent(Employee employee) throws InfrastructureException {

        try {
            HibernateUtil.getSession().save(employee);
        } catch (HibernateException ex) {
            throw new InfrastructureException(ex);
        }
    }

    // ********************************************************** //

    public void makeTransient(Employee employee) throws InfrastructureException {

        try {
            HibernateUtil.getSession().delete(employee);
        } catch (HibernateException ex) {
            throw new InfrastructureException(ex);
        }
    }

}

Uses Hibernate and Struts

In this section you will be learn how to use hibernate with struts to construct robust web applications with JBuilder.

Call DAO operations in the Action code

  1. Go to EmployeeAction.java file (Project Pane > <Project Source> node > hibernateproject node > and double click in the EmployeeAction.java).
  2. Replace the all code by the below code, format code (SHIFT + ALT + K) and save all.
package hibernateproject;

import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForward;

import org.apache.struts.action.Action;

public class EmployeeAction extends Action {
    public ActionForward execute(ActionMapping actionMapping,
                                 ActionForm actionForm,
                                 HttpServletRequest servletRequest,
                                 HttpServletResponse servletResponse) {

        try {
            EmployeeActionForm employeeForm = (EmployeeActionForm) actionForm;
            Employee employee = new Employee();
            EmployeeDAO dao = new EmployeeDAO();

            String action = (String) servletRequest.getParameter("action");

            if (action != null) {

                employee.setIdEmployee(employeeForm.getIdEmployee());
                employee.setName(employeeForm.getName());
                employee.setAge(employeeForm.getAge());
                employee.setGendre(employeeForm.getGendre());
                employee.setSalary(employeeForm.getSalary());
            }
            ;

            if (action.equals("Post")) {

                dao.makePersistent(employee);
                HibernateUtil.commitTransaction();

            } else if (action.equals("Update")) {

                HibernateUtil.commitTransaction();

            } else if (action.equals("Delete")) {

                dao.makeTransient(employee);
                HibernateUtil.commitTransaction();

            } else if (action.equals("Find")) {

                employee = (Employee) dao.findByName(employeeForm.getName()).
                           iterator().next();
                servletRequest.setAttribute("employee", employee);
            }

        } catch (InfrastructureException ex) {
            // Rethrow as a checked exception

            HibernateUtil.rollbackTransaction();
            throw new Exception(ex);

        } finally {
            HibernateUtil.closeSession();
            return actionMapping.findForward("employee");
        }

    }
}

Mapping Beans to the Database

Making JBuilder includes *.xml files in the source WAR file

  1. Go to Project > Project Properties > Build section > Resource node.
  2. Find "xml" in the Listbox and select them.
  3. Check Copy radiobox. Now, appears Copy in the xml line.
  4. Click in the Ok button to finalize.

Configuring Database in the Hibernate

  1. Go to the Project Pane and Find <Project Source> node.
  2. Click with right button in this node and go to New > File...
  3. Set "Name" field with "hibernate.cfg" value.
  4. Set "Type" field with "xml" value.
  5. Click in the Ok button.
  6. The hibernate.cfg.xml file was created in the <Project Source> node and your souce code appears in the Code Editor.
  7. Put the below source code to the file, format it (Shift + ALT + K) and Save All.
<!DOCTYPE hibernate-configuration PUBLIC
	"-//Hibernate/Hibernate Configuration DTD//EN"
	"http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd">
<hibernate-configuration>
  <session-factory>

    <!-- Don't forget to copy your JDBC driver to the lib/ directory! -->
    <!-- Settings for a local MySQL database. -->
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>

    <property name="connection.url">jdbc:mysql://localhost:3306/employeecatalog</property>
    <property name="connection.username">root</property>

    <property name="connection.password">root</property>
    <!--
      Use the C3P0 connection pool.
      <property name="c3p0.min_size">3</property>
      <property name="c3p0.max_size">5</property>

      <property name="c3p0.timeout">1800</property>
    -->
    <!-- Use the Hibernate built-in pool for tests. -->
    <property name="connection.pool_size">3</property>

    <!-- Print SQL to stdout. -->
    <property name="show_sql">false</property>
    <!-- CityCatalog mapping files. -->
    <mapping resource="hibernateproject/Employee.hbm.xml"/>

  </session-factory>
</hibernate-configuration>

Mapping the Employee Class

  1. Go to the Project Pane and Find "hibernateproject" node in the <Project Source> node.
  2. Click with right button in the node and go to New > File...
  3. Set "Name" field with "Employee.hbm" value.
  4. Set "Type" field with "xml" value.
  5. Click in the Ok button.
  6. The Employee.hbm.xml file was created in the <Project Source>/hibernateproject node and your souce code appears in the Code Editor.
  7. Put the below source code to the file, format it (Shift + ALT + K) and Save All.
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping SYSTEM
			"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >

<hibernate-mapping package="hibernateproject">
  <class name="Employee" table="employee" lazy="true">

    <!-- We can't change the creation time, so map it with update="false". -->
    <id name="idEmployee" column="idEmployee" type="java.lang.Integer">

      <generator class="identity"/>
    </id>
    <property name="name" column="name" type="java.lang.String" update="true" not-null="true"/>

    <property name="age" column="age" type="java.lang.Integer" update="true" not-null="true"/>

	 <property name="gendre" column="gendre" type="java.lang.String" update="true" not-null="true"/>

    <property name="salary" column="salary" type="java.lang.Double" update="true" not-null="true"/>

  </class>
</hibernate-mapping>

Creating Database in MySQL

In this pass will be created the Database Tables for this tutorial.

  1. Create your database with "employeecatalog" value.
  2. Create the table employee with the below fields and save all.
Column Name
Type
Additional Information
idEmployee INTEGER Primary Key, Not Null and AutoInc
name VARCHAR(30) Not Null
age INTEGER Not Null
gendre VARCHAR(15) Not Null
salary DOUBLE Not Null
 

Ready! Execute your application. Good Lucky!

Alternatives to the Hibernate

The are alternatives to the Hibernate framewok, look:

  • EJB: Sun especification for Enterprise applications. Use Entity Beans (CMP and BMP) for persistence. Many manufactures in the market. The BES product of the Borland (deploy) is one alternative with JBuilder for RAD construct of the CMPs and BMPs.
  • JDO: Sun especification for object persistance. Many manufactures in the market.


Server Response from: ETNASC01