Sunday, July 25, 2010

CRUD using Hibernate Annotations with Netbean 6.0


In this article we will discuss about the basic make the process of Create, Read, Update and Delete using Hibernate as the Framework and Netbean as its IDE, Hibernate configuration usually always never loose with Spring configuration, but on this occasion I will elaborate on Hibernate without Spring, with the aim if you want to create desktop applications the Spring configuration is not required.

Before we start it's good to know a class-library will be need it takes to build applications using Hibernate Annotations, as follows:


Now how do I enter all libraries into the project properties that we will create? Enough that we follow these steps: from the Toolbar select Tools then clicked, will popup dropdown menu, then select Libraries then will come out the window box with title "Library Manager", then press the "New Library", then come out again the window box with the title "New Library", fill in the word "Hibernate” in the Library Name text box, continue to select the "Class Libraries" dropdown box Type Library, then press OK, then select Hibernate library jar file that has been listed above to the folder which we have previously determined by press the button "Add Jar / Folder" on the tab "Classpath", after the files sent it will displayed like this:

After that, press "OK" button, now the discussion will be continued by creating a new project in the IDE Netbean. After creating a new project, whether web or desktop project, the project window will as follows:

After creating a project, first enter the hibernate libraries by right click on the library folder, then click "Add Library" and will come out a window with the title "Add Library", forwarded by selecting the necessary library which is selected, then "Add Library", then the Library folder in the project will display the entire library jar file that will required in the application to be built.

After all required libraries are prepared in the library folder, now it's time to discuss making CRUD using Hibernate, before you start coding with java class we need to know beforehand the basic configuration that must be met, so that Hibernate can work properly, this configuration involves an xml file that will be placed in the root folder of the folder "Source Packages", these files must be named "hibernate.cfg.xml" and the contents of the file will be as follows:


<?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>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/latih</property>
<property name="connection.username">root</property>
<property name="connection.password">admin</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>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">none</property>

<mapping class="xxx.TabelSiswa"/>
</session-factory>
</hibernate-configuration>

From the source xml above configuration, there are several properties that must exist to build hibernate based application framework, the following list and description for more details can be viewed on the link http://www.hibernate.org/hib_docs/reference/en/html/session-configuration.html:

- connection.driver.class, This property is used as a determinant of what database driver will be used to connect to database.

- connection.url, This property is used to determine the url destination of database to be used as a connection to the database.

- connection.username, property user name that is used to access databases.

- connection.password, property password that is used to access databases.

- connection.pool.size, property that is used as maximum limit how many connections may used to connect to the database.

- dialect, property that determines what types dialect that will be used, adjusted to the type of database used.

- current_session_context_class, property that is used to treat the session context, the choice is jta | thread | managed | custom.Class.

- cache.provider_class, property to specify a custom class that will be used to CacheProvide.

- show_sql, property to show that the execution of SQL commands the choice can be true or false.

- hbm2ddl.auto, property for automatic validation or export a database schema to the SessionFactory when made, and create-drop properties directly in the schema will drop when the SessionFactory is closed. When the properties set to none means not to do anything against the database schema.

While for a line of code <mapping class="xxx.TabelSiswa"/> is command for mapping an Annotation Model classes so that it can be read by hibernate.cfg.xml file, the amount of mapping will be more or less depending on the number of class models are made to support your application.

When finished with the configuration now the time to make a model class that represents a table in a database. As an example we will create a class "TabelSiswa" which will be stored in the package "xxx", the code as follow:

package xxx;

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "tbl_siswa")
public class TabelSiswa implements Serializable{
@Id
@GeneratedValue
private int id;

@Column(name="no_induk", nullable=false,length=10)
private String nomorInduk;

@Column(name="nama", nullable=false,length=30)
private String nama;

@Column(name="alamat", nullable=false,length=45)
private String alamat;

public int getId() {
return id;
}

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

public String getNomorInduk() {
return nomorInduk;
}

public void setNomorInduk(String nomorInduk) {
this.nomorInduk = nomorInduk;
}

public String getNama() {
return nama;
}

public void setNama(String nama) {
this.nama = nama;
}

public String getAlamat() {
return alamat;
}

public void setAlamat(String alamat) {
this.alamat = alamat;
}
}

The above code represents a table in a MySQL database called "tbl_siswa" with field names specified in the @ Column properties above, from source code "TabelSiswa" above we can see some syntax code that begins with "@" sign, which is called Annotations briefly will be explained the meaning of each following the above commands, but for more details can be viewed on the following link http://www.hibernate.org/hib_docs/annotations/reference/en/html/entity.html:

- @Entity, serves to define a model class is an bean associated with the POJO persistence.

- @Table, serves to connect an Entity classes on a table in a database schema.

- @Id, serves to define the propery of the entity bean fields that will serve as the primary key.

- @GeneratedValue, serves to define generator type that is used to obtain the value of identifier @Id.

- @Column, serves as the property of field mapping a field in the table in the database.

Then create a java class file that called HibernateUtility.java used as a Session Factory, which connects a process which was generated programmatic transaction with hibernate configuration system that has been predetermined. The source code of HibernateUtility would this as follow:

package xxx;

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

public class HibernateUtil {
private static final SessionFactory sessionFactory;

static{
try{
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
}catch(Throwable th){
System.err.println("Initial SessionFactory creation failed"+th);
throw new ExceptionInInitializerError(th);
}
}

public static SessionFactory getSessionFactory(){
return sessionFactory;
}
}

When finished making HibernateUtility.java now begin discussing the process of Create, Read, Update and Delete, which will be stored in the package "xxx.client", here is source code "CreateData.java" which contains examples of commands to enter data:

package xxx.client;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import xxx.HibernateUtil;
import xxx.TabelSiswa;

public class CreateData {
public static void main(String[] args) throws Exception {
SessionFactory sessFact = HibernateUtil.getSessionFactory();
Session sess = sessFact.getCurrentSession();
Transaction tr = sess.beginTransaction();
TabelSiswa stu = new TabelSiswa();
stu.setNama("Yudhi");
stu.setNomorInduk("100");
stu.setAlamat("Jl. Sukajadi No. 10");
sess.save(stu);
tr.commit();
System.out.println("Successfully inserted");
sessFact.close();
}
}

Discussing what is written on the source code in the first row to third in the method "main" written to initialize Hibernate Session and Transaction, then proceed with initialization "TabelSiswa" that connects directly to the table "tabel_siswa" in the database, with the amount of variables to the method "set" and then inserted into the method "save" that are under the initialization Session, it has been a process of "insert into" on the table in database. Then close the command with "commit" to the execution of insert data to table and "close" to terminate the Session initialization.

Followed by "ReadData.java" source code:


package xxx.client;

import java.util.Iterator;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import xxx.HibernateUtil;
import xxx.TabelSiswa;

public class ReadData {
public static void main(String[] args) throws Exception {
SessionFactory sessFact = HibernateUtil.getSessionFactory();
Session sess = sessFact.getCurrentSession();
Transaction tr = sess.beginTransaction();
Query query = sess.createQuery("from TabelSiswa");
List result = query.list();
Iterator it = result.iterator();
System.out.println("id sname sroll scourse");
while(it.hasNext()){
TabelSiswa st = (TabelSiswa)it.next();
System.out.print(st.getId());
System.out.print(" "+st.getNomorInduk());
System.out.print(" "+st.getNama());
System.out.print(" "+st.getAlamat());
System.out.println();
}
sessFact.close();
}
}

Slightly different from the source code before, the above command is to display data from tables or the same with the command "select" in the query, but if you use Hibernate enough with the "createQuery" command and specify the name of instant mapping table, it’s enough to retrieve the data, the need to take data can be changed based on the 'where clause' as required. It also required List and Iterator class to parse the class that will encapsulate the smallest object.


Followed by "UpdateData.java" source code:

package xxx.client;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import xxx.HibernateUtil;
import xxx.TabelSiswa;

public class UpdateData {
public static void main(String[] args) throws Exception{
SessionFactory sessFact = HibernateUtil.getSessionFactory();
Session sess = sessFact.getCurrentSession();
Transaction tr = sess.beginTransaction();
TabelSiswa st = (TabelSiswa)sess.load(TabelSiswa.class,4);
st.setAlamat("Jl. Lodaya No. 125");
tr.commit();
System.out.println("Update Successfully");
sessFact.close();
}
}

For the source code UpdateData processes that occurred not far different from what happened in the process CreateData, little things that differentiate only on the line "TabelSiswa st = (TabelSiswa) sess.load (TabelSiswa.class, 4);" that is used to retrieve data that will edited into the database with the entity model "TabelSiswa" and make any changes, after which it did commit. And the last is deleting process in "DeleteData.java" file, source code as follows:

package xxx.client;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import xxx.HibernateUtil;
import xxx.TabelSiswa;

public class DeleteData {
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub

SessionFactory sessFact = HibernateUtil.getSessionFactory();
Session sess = sessFact.getCurrentSession();
Transaction tr = sess.beginTransaction();
TabelSiswa st = (TabelSiswa)sess.load(TabelSiswa.class,4);
sess.delete(st);
System.out.println("Deleted Successfully");
tr.commit();
sessFact.close();

}
}

DeleteData source code process that occurs is not much different from what happens in UpdateData process, little things that differentiate only on the line "sess.delete(st);" that is used to retrieve data to be deleted from the database with the entity model "TabelSiswa" after that do commit.

Ok good luck! Maybe for this time this is trick that can be shared with the reader hope it useful, if there is a shortage or entries which can improve please feel free to give comment.

Here's a list of links that can be used to download the required jar files:

- http://antlr.org/

- http://www.java2s.com/Code/Jar/Spring-Related/cglib-nodep-2.1_3.jar.htm

- http://sourceforge.net/project/showfiles.php?group_id=56933

- http://sourceforge.net/project/showfiles.php?group_id=40712

- http://commons.apache.org/downloads/

- http://www.dom4j.org/download.html

- http://sourceforge.net/project/showfiles.php?group_id=93232

- http://logging.apache.org/log4j/1.2/download.html