Java Developing- Hibernate and JPA annotations

I have just spent
sometime experimenting to see how hibernate annotations and generics
can work together to give us an application that will also add more
Object Oriented techniques to the Transaction Script Pattern[Fowler
2002].

We will need a MySQL database, and JDK6 should work on
JDK5(but I’m testing on JDK6.) and Hibernate 3.

The structure
of the TestProject in Eclipse IDE will be as follows:

The dependencies that are needed are
listed here as seen in Eclipse IDE:

Setup your db and create
a database called "myworld" Then create the table Users:

CREATE TABLE users (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(30),
surname VARCHAR(50),
cur_timestamp TIMESTAMP(8)
);


Next grant a user permissions on database. I will use "user"
and password "password".

Next
we create the Users.java class(this will have the annotations)

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

package testproject.database.pojo;

import java.io.Serializable;
import java.sql.Timestamp;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * @author gabriel
 *
 */
@Entity
@Table(name="users")
public class Users implements Serializable{
   
    private int id;   
    private String name;   
    private String surname;   
   
    private Timestamp curtimestamp;
    /**
     *
     */
    public Users() {
        // TODO Auto-generated constructor stub
    }

    @Id
    public void setId(int id) {
        this.id = id;
    }
    @Id
    public int getId() {
        return id;
    }

    @Column(updatable = true, name = "name", nullable = false, length=30)
    public void setName(String name) {
        this.name = name;
    }
    public String getName() {
        return name;
    }

    @Column(updatable = true, name = "surname", nullable = false, length=50)
    public void setSurname(String surname) {
        this.surname = surname;
    }
    public String getSurname() {
        return surname;
    }

    @Column(updatable = false, name = "cur_timestamp")
    public void setCurtimestamp(Timestamp curtimestamp) {
        this.curtimestamp = curtimestamp;
    }
    @Column(updatable = false, name = "cur_timestamp")
    public Timestamp getCurtimestamp() {
        return curtimestamp;
    }

   
   
   

}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

After this create the hibernate.cfg.xml file under your source
folder:

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"&gt;
<hibernate-configuration>
  <session-factory>
 
      <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/myworld</property>
        <property name="connection.username">user</property>
        <property name="connection.password">password</property>

        <!– JDBC connection pool (use the built-in) –>
        <property name="connection.pool_size">1</property>

        <!– SQL dialect –>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
       
   
    <mapping class="testproject.database.pojo.Users"/>
   
  
  </session-factory>
</hibernate-configuration>

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

Now we go on and we create the DatabaseDAO.java class. This will
have generics and will be the place where more Object Oriented
Concepts are employed to the Transaction Script Pattern.

The
code is as follows:

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

package testproject.database;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

/**
 * @author gabriel
 * @param <T>
 *
 */
public class DatabaseDAO<T> {

    private static SessionFactory sessionFactory;
    
    private String query;

    /**
     *
     */
    public DatabaseDAO() {
        // TODO Auto-generated constructor stub
    }

    public  List<T> getT(){
        
        List items;
        
        
        try {
                        
            AnnotationConfiguration ac = new AnnotationConfiguration().configure();
            
            sessionFactory = ac.buildSessionFactory();
            
            Session session = sessionFactory.openSession();
            
            
            String queryStatement = getQuery();
            
            Query query = session.createQuery(queryStatement);
            
            items = query.list();
            
            
        
        } catch (Throwable ex) {
            // Log exception!
            throw new ExceptionInInitializerError(ex);
        }

        return items;
    }

    public void setQuery(String query) {
        this.query = query;
    }

    public String getQuery() {
        return query;
    }
    
    
    
    
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////

Here I have only on method a retrieval from the users table. You
can add more functionality. The function is a generic getT() method.
This means we are not bound to any database table.

Now we
create a test class Main.java

/////////////////////////////////////////////////////////////////////////////////////////////////////////

package testproject;

import java.util.List;

import testproject.database.DatabaseDAO;
import testproject.database.pojo.Users;
/**
 * @author gabriel
 *
 */
public class Main {

    /**
     * main method
     */
    public static void main(String… arhs) {
       
        String T = "Users";
       
        DatabaseDAO<Users> dbDAO = new DatabaseDAO<Users>();
       
        dbDAO.setQuery("from "+T);
        List<Users> users = dbDAO.getT();
       
        if(users!=null && users.size()>0){
            for(Users user : users)
            System.out.println("Hi I am "+user.getName());
        }
       
    }

}

/////////////////////////////////////////////////////////////////////////////////////////////////////////

In this class we implement business logic and name the table that
we want to call. My output on running this was:

Hi
I am gabriel

There we are. The DatabaseDAO uses
generics so even if we had another table in the database we could
still retrieve its data by simply creating the pojo for it and
implementing the business logic! No change to the programmatic logic.
With annotations we did not need to have mapping files This leads to
a further reduction in amount of work done and files generated. We
have a smaller faster application.

Next time I will add liquibase and examine its use for database management.

Advertisements

About gjcbell

I am the Cloud Architect at IBM. I work in and create Hybrid Cloud solutions. These are solutions that have an on premise facet and multi Cloud platform facet. My area of focus spans the Bluemix Platform, IBM Cloud Private as well as cloud brokerage.
This entry was posted in Computers and Internet. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s