Thursday, September 4, 2014

Your first Hibernate project with MySQL



This post is the first post which is about Hibernate. I want to give you a brief introduction about, how to use Hibernate and configure Hibernate files with MySQL. This will be the widest post in this blog. 


1. Create a database for the project



I'm going to create Database called shop and table within it called mobiles. I have already added some data into this table as follows. For testing purposes I have added more data into that table. You can download full sql script below.



create database shop;

use shop; 

create table mobiles(
 id int primary key auto_increment,
 brand varchar(50),
 model varchar(50),
 price int 
);

insert into mobiles (brand, model, price) values
('Nokia','Lumia 1020',700),
('Sony','Z2',600),
('HTC','OneMax',800),
('Apple','5S',900);



2. Create simple Java Application



No need to demonstrate this. Because this is very easy. You just need to create simple Java application and name it as "HibernateDemo" but don't create the main class(uncheck the tick).







3. Adding Hibernate and MySQL libraries



In this tutorial series I am using NetBeans 8.0 it comes with Hibernate 4 libraries. You know how to add library into your project. Just right click on the Libraries in your project. Then click on Add library. Then select Hibernate 4.x and add it. 



In this project we use MySQL. So we need to add MySQL JDBC Driver also. 


4. Create new connection



Now I'm going to create a new connection with the database that I have created. Just go to Services tab( If you can't find it, go to Window in the menu ). Then right click on it and do as follows.





Select the Driver


Type the database name(shop) and type the MySQL password.
If connection is succeeded go to Next


Nothing to change, click Next


Finish it




5. Add Hibernate Configuration file














Finally you did it. But you need to change some settings to easier future works.


  • Adding hibernate.show_sql property
Hibernate uses HQL( Hibernate Query Language ). This property is used to enable the logging of all the generated sql statements to the console. Mainly this is used for trouble shooting. 






Then you can add hibernate.format_sql property also.


  • Add hibernate.query.factory_class property
This is use to map hibernate queries to sql queries.











6. Add Hibernate Reverse Engineering file.













To learn more about Reverse Engineering Wizard, Click here.

7. Adding Hibernate mapping file and POJOs from database














Now your project has been configured to use Hibernate.  Lets see how to run simple HQL query.


8. Run HQL command




Right click on Hibernate.cfg.xml file
Select Run HQL Query






This is the way to configure your project that enables to use Hibernate. In next post you will learn how to use Hibernate to insert, update and delete data in your database. Here is the zipped project file in NetBeans.