You are on page 1of 5

Downloading and creating a simple project to play with HIBERNATE Juliano Marcos Martins http://jmmwrite.wordpress.

com

First Step: Download Hibernate libs Go to http://www.hibernate.org/ Click Download Select the Binary Release, Production and click download:

Choose the file that you want, in our case, the zip file. The zip file have ~ 24 mb. Creating a project with Eclipse We will create a new dynamic Web project into Eclipse. It will be a Web project because soon I'll post the part II of this tutorial, in this part we will create a simple page. Te create the new project go to: File New Dynamic Web Project We will call it from HiberTest. Now, we just have to unzip the file that we just download, and copy the jar files to the WEBINF/lib folder of our project, note that you need to copy the Hibernate*.jar too. Also, I'll create a connection with IBM DB2, then, I just drop the DB2 JDBC libs into the same folder. If you will work with other Database, remember to download and drop the correct files and change Hibernate settings. In our app, we will have a simple file that will execute a common insert operation. In the second part of the tutorial, I'll create a JSP file that calls a servlet that Insert/Delete/Update/List.

We will work with Costumers. After create our project, we will create a package called beans, in this package we will create a class called Costumer. We will map this class into Hibernate using annotations, you can see more details about this in the class body. You can map classes working directly with XML configuration files. In this tutorial we choose annotations cause I thins that its easy to understand. The class body is:
package beans; import javax.persistence.Entity; import javax.persistence.Id; @Entity // this tell to Hibernate that this class its a entity in the database public class Costumer { @Id // this tell to hibernate that id its the primary key of our table private int id; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }

We have to create two files to configure Hibernate and log4j (this will log messages to us). The first file, will be created under /src folder, and the file name is hibernate.properties , the file content is:
hibernate.query.substitutions true 1, false 0, yes 'Y', no 'N' ## DB2 hibernate.dialect org.hibernate.dialect.DB2Dialect hibernate.connection.driver_class com.ibm.db2.jcc.DB2Driver ## Specify the host and database name hibernate.connection.url jdbc:db2://localhost:50000/XXXX ## Specify schema, username and password of the database hibernate.default_schema XXX hibernate.connection.username XXX hibernate.connection.password XXX ## Some Hibernate settings hibernate.connection.pool_size 1 hibernate.proxool.pool_alias pool1 hibernate.show_sql true hibernate.order_updates true

hibernate.max_fetch_depth 1 hibernate.default_batch_fetch_size 8 hibernate.jdbc.batch_versioned_data true hibernate.jdbc.use_streams_for_binary true hibernate.cache.region_prefix hibernate.test hibernate.cache.provider_class org.hibernate.cache.HashtableCacheProvider

The second file its under /src and will be called log4j.properties :
log4j.rootCategory=DEBUG, Default log4j.appender.Default=org.apache.log4j.FileAppender log4j.appender.Default.File=test.log log4j.appender.Default.layout=org.apache.log4j.PatternLayout # A default format: [Category] msg\n log4j.appender.Default.layout.ConversionPattern=[%c{1},%p] %m%n # A format useful for debugging concurrency: [Category,thread,elapased_ms] msg\n #log4j.appender.Default.layout.ConversionPattern=[%c{1},%t,%r] %m%n # Do not truncate if it aleady exists. log4j.appender.Default.Append=true

After you finish the Hibernate and log4j settings, we will create 2 classes. Under /src, lets create a package called util. This new 2 classes will be created under this package. The first class will responsible to create Hibernate sessions, it will be called HibernateUtil.java. The source code for this class its:
package util; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.cfg.AnnotationConfiguration; import beans.Costumer; // we import our class here public abstract class HibernateUtil { private static org.hibernate.SessionFactory fabrica; static { AnnotationConfiguration conf = new AnnotationConfiguration(); conf.addAnnotatedClass(Costumer.class); // we add the Costumer class here // if you create more classes at your proj., you must add here fabrica = conf.buildSessionFactory(); } public static Session getSession() { return fabrica.openSession(); } public static void closeSession() throws HibernateException { } }

The other class will be a util class that just create tables for us, based on our beans. This class connect in the database and create the table. To do this we will just execute the class DataGeneration:
package util; import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.tool.hbm2ddl.SchemaExport; import beans.Costumer; /** * Create tables based on beans */ public class DataGeneration { public static void main(String[] args) { AnnotationConfiguration conf = new AnnotationConfiguration(); conf.addAnnotatedClass(Costumer.class); SchemaExport sE = new SchemaExport(conf); sE.create(true, true); } }

After write the class, you can execute it as a Java Application. After execute the class, we must check that we connect to our database and create the table. The output must be something like:
drop table schema.Costumer create table schema.Costumer primary key (id)) (id integer not null, name varchar(255),

This just told us that our Hibernate sessions are perfect! It it does not work, verify the error and fix it. Please, ensure that you have imported the correct classes in your classes, because maybe Eclipse can import other classes and this can make your application don't work. Its common I receive e-mails from people that just import the wrong classes. Please, pay attention. Next step is create our test class. We will create a simple class that will perform a Insert. This class will be created inside our util folder and its name is test. The class body is:
package util; import org.hibernate.Session; import beans.Costumer; public class test { /** * Main method */ public static void main(String[] args) { // creating a costumer Costumer cost1 = new Costumer(); // setting attributes cost1.setId(1);

cost1.setName("John"); // Geting a Hibernate session Session session = HibernateUtil.getSession(); // Starting the transaction session.beginTransaction(); //Inserting the costumer session.save(cost1); //Commiting the transaction session.getTransaction().commit(); } }

The final step its execute our class. Execute it as a Java Aplication. In the output you must see something like this:
Hibernate: insert into schema.Costumer (name, id) values (?, ?)

Ok, this can show you how to download and play with Hibernate. Now, I suggest that you play with delete, merge, update alone! If do you want the source code, ask me here. Soon I'll create the part II of this tutorial that will show all the operations! Enjoy! Juliano Marcos Martins http://jmmwrite.wordpress.com

You might also like