Hibernate, PostgreSQL, Ubuntu, NetBeans IDE (Part 3)

To complete the picture, let's use the traditional (that is, old) Hibernate mechanism, i.e., via XML files, rather than via the annotations shown yesterday. It's definitely trickier, with many more places where typos can occur, but that's why it's the old mechanism. I do not recommend this approach. I recommend the approach shown yesterday. The other players in this scenario include PostgreSQL, as outlined in the previous blog entries in this series.

Here's the structure of the module, replacing the code shown yesterday:

Here's the Employee class, notice that it has no annotations:

import java.io.Serializable;
import java.util.Date;

public class Employees implements Serializable {
    
    private int employeeId;
    private String firstName;
    private String lastName;
    private Date dateOfBirth;
    private String phoneNumber;
    private String junk;

    public int getEmployeeId() {
        return employeeId;
    }

    public void setEmployeeId(int employeeId) {
        this.employeeId = employeeId;
    }

    public String getFirstName() {
        return firstName;
    }

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

    public String getLastName() {
        return lastName;
    }

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

    public Date getDateOfBirth() {
        return dateOfBirth;
    }

    public void setDateOfBirth(Date dateOfBirth) {
        this.dateOfBirth = dateOfBirth;
    }

    public String getPhoneNumber() {
        return phoneNumber;
    }

    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

    public String getJunk() {
        return junk;
    }

    public void setJunk(String junk) {
        this.junk = junk;
    }

}

And here's the Hibernate configuration file:

<?xml version="1.0"?>
<!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="hibernate.connection.driver_class">org.postgresql.Driver</property>
        <property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/smithdb</property>
        <property name="hibernate.connection.username">smith</property>
        <property name="hibernate.connection.password">smith</property>
        <property name="hibernate.connection.pool_size">1</property>
        <property name="hibernate.default_schema">public"</property>
        <property name="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
        <property name="hibernate.current_session_context_class">thread</property>
        <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
        <property name="hibernate.show_sql">true</property>
        <mapping resource="org/db/viewer/employees.hbm.xml"/>
    </session-factory>
</hibernate-configuration> 

Next, the Hibernate mapping file:

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

    <class name="org.db.viewer.Employees" 
           table="employees" 
           schema="public" 
           catalog="smithdb">

        <id name="employeeId" column="employee_id" type="int">
            <generator class="increment"/>
        </id>

        <property name="firstName" column="first_name" type="string" />
        <property name="lastName" column="last_name" type="string" />
        <property name="dateOfBirth" column="date_of_birth" type="date" />
        <property name="phoneNumber" column="phone_number" type="string" />
        <property name="junk" column="junk" type="string" />
        
    </class>
    
</hibernate-mapping>

Then, the "HibernateUtil" file, for providing centralized access to the Hibernate "SessionFactory":

import java.net.URL;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;

public class HibernateUtil {

    private static final SessionFactory sessionFactory;
    
    static {
        try {
            // Create the SessionFactory from standard (hibernate.cfg.xml) 
            // config file.
            String res = "org/db/viewer/employees.cfg.xml";
            URL myURL = Thread.currentThread().getContextClassLoader().getResource(res);
            sessionFactory = new AnnotationConfiguration().configure(myURL).buildSessionFactory();
        } catch (Throwable ex) {
            // Log the exception. 
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
    
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
    
}

Finally, the "createKeys" in the ChildFactory:

@Override
protected boolean createKeys(List list) {
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    Transaction transac = null;
    try {
        transac = session.beginTransaction();
        Query query = session.createQuery("from Employees");
        list.addAll(query.list());
    } catch (HibernateException he) {
        Exceptions.printStackTrace(he);
        if (transac != null){
            transac.rollback();
        }
    } finally {
        session.close();
    }
    return true;
}

Note that Constantine Drabo has a similar article here.

Run the application and the result should be the same as yesterday.

Comments:

Post a Comment:
  • HTML Syntax: NOT allowed
About

Geertjan Wielenga (@geertjanw) is a Principal Product Manager in the Oracle Developer Tools group living & working in Amsterdam. He is a Java technology enthusiast, evangelist, trainer, speaker, and writer. He blogs here daily.

The focus of this blog is mostly on NetBeans (a development tool primarily for Java programmers), with an occasional reference to NetBeans, and sometimes diverging to topics relating to NetBeans. And then there are days when NetBeans is mentioned, just for a change.

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
12
13
14
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today