Hibernate Hello World Program (Hibernate Insert Query)
|
Hibernate »
On May 26, 2011 | { 29 Comments }
|
Tweet
|
Mates, hear is the first program in hibernate like saving an object into the database (don’t think we are inserting a record into the database
that is the case in JDBC, in hibernate we are just saving an object into database, means inserting only) hope you got my contention, as of now am giving this as normal console based java application, actually it’s bit tedious to set the class path every time for all the jar files but you must know this too.
From the next example i will give all the applications in the Eclipse
As i told you earlier, these are the files we require to shape an hibernate program..
- Product.java (My POJO class)
- Product.hbm.xml (Xml mapping file )
- hibernate.cfg.xml (Xml configuration file)
- ClientForSave.java (java file to write our hibernate logic)
Product.java:
private int productId;
private String proName;
private double price;
public void setProductId(int productId)
{
this.productId = productId;
}
public int getProductId()
{
return productId;
}
public void setProName(String proName)
{
this.proName = proName;
}
public String getProName()
{
return proName;
}
public void setPrice(double price)
{
this.price = price;
}
public double getPrice()
{
return price;
}
Product.hbm.xml:
<?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="Product" table="PRODUCTS"> <id name="productId" column="pid" > <generator class="assigned" /> </id> <property name="proName" column="pname" /> <property name="price"/> </class> </hibernate-mapping>
In this mapping file, my Product class is linked with PRODUCTS table in the database, and next is the id element, means in the database table what column we need to take as primary key column, that property name we need to give hear, actually i have been given my property name productId which will mapped with pid column in the table.
And proName is mapped with pname column of the PRODUCTS table, see i have not specified any column for the property price, this means that, our property name in the pojo class and the column name in the table both are same.
Remember: the first 3 lines is the DTD for the mapping file, as a programmer no need to remember but we need to be very careful while you are copying this DTD, program may not be executed if you write DTD wrong, actually we have separate DTD’s for Mapping xml and Configuration xml files.
hibernate.cfg.xml:
<?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> <!-- Related to the connection START --> <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver </property> <property name="connection.url">jdbc:oracle:thin:@www.java4s.com:1521:XE</property> <property name="connection.user">user</property> <property name="connection.password">password</property> <!-- Related to the connection END --> <!-- Related to hibernate properties START --> <property name="show_sql">true </property> <property name="dialet">org.hibernate.dialect.OracleDialect </property> <property name="hbm2ddl.auto">update </property> <!-- Related to hibernate properties END --> <!-- Related to mapping START --> <mapping resource="product.hbm.xml" /> <!-- Related to the mapping END --> </session-factory> </hibernate-configuration>
In this configuration file i have been given my Oracle database connection properties, if you are using MySql then just specify your database related details actually its depends on you.
ClientForSave.java
import org.hibernate.*;
import org.hibernate.cfg.*;
public class ClientForSave {
public static void main(String[] args)
{
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory factory = cfg.buildSessionFactory();
Session session = factory.openSession();
Product p=new Product();
p.setProductId(101);
p.setProName("iPhone");
p.setPrice(25000);
Transaction tx = session.beginTransaction();
session.save(p);
System.out.println("Object saved successfully.....!!");
tx.commit();
session.close();
factory.close();
}
}
Now compile all .java files and run ClientForSave.java and check the output
Output Eclipse
![]() |
![]() |
In The Database
![]() |
![]() |
Note:
- Make sure all .class, .java, .xml files are exist in the same folder
- Before you compile and run this application, ensure you set the class path for all 12 jars files, this is tedious like what i told you earlier, we can avoid this process from the next example with Eclipse, a real time tool
- except select operation, all other operations must be in the Transaction Scope
|





Hello java4s team,
I modified your programs by just adding System.out.println statements to analyze the control flow.. Am getting doubt in that. please help
Mydoubt
1. why setter method of getproductid is called after getter method of getproductid
2. why getter are methods are called from the lines “before commit and after commit” in the console as they are already get na?
Thank you seeing this post..
Hi vaseem,
> Actually the priority will be, getter methods will be called only after setter methods.
> Before commit always getter methods will be called because, there is a chance to modify the values before commit ?
Hope you understand.
———————————–
We are requesting you to send lengthy text messages to our mail id rather writing here
Hello java4s Team,
Hats off to Tremendous service of yours……….
I request you to maintain a forum where all users can post their questions, can communicate with other users also in explaining queries. It will be very much flexible to learn the subject when it is shared, communicated with all…
Thank You!
Yeah vaseem,
we are thinking the same,
very soon we are going to launch one forum.
It’s a great website for beginners and professionals too. It quite helpful both in terms of concepts and examples. Kindly put a back and forth or next link in the detail tutorial page to next related article.
@soumen
Thank you soumen, yeah we are keep getting this suggestion of back-forth buttons from the users, we will implement this very soon.
please provide how to implement singleton pattern in hibernate
hope u provide this.
thanking you
It is a Best Suitable Tutorial for Biginners. I got exact flow of applications like Hibernate and Struts.
Thanks to Java4s Team.
Madhu.chimata
Ya of course ! this site very useful for us
@Harish
We will provide for sure.
@Madhu,@Shiva
Thanks for your feedback, feel free to share this article, will be useful to all java freshers.
can u just tell to me .where i put cfg.xml and hbm.xml in eclipse.can i put on src folder.
@prasanta kumar routray
yeah src folder is fine, please check the next article(Hibernate Hello World Program in Eclipse) still if you have any doubt.
Sir i Want to know that why we put configure file out from the package(java).Can we put it with java files…please tell me about it..Thank you Sir.
@Anand
Configuration files must be in the folder contains all your classes files, just play by removing and adding the configuration files here to there
so that you will be able to understand exactly whats going, hope you understand.
hi sir i m getting dis message
log4j:warn no appenders could be found for logger
(Org.hibernat.cfg.Environment)
so how to solve
thanks
@sanjay
Actually that warning is about logging, as of now we no need to care about that, even i have show that in the output screen too
.
Sir in the code ClientForSave.java only 1 row is inserted is (101,iphone,25000) but result shows that there are 4 rows inserted in the database. How to insert multiple rows? by creating multiple referrence of Product class?
Pls Pls reply Sir.
@Saptak
Bulk you can do in future concepts.
As of now you can work only with single object only. As you are fresher you need to know some more concepts
, move one by one so that you will be able to understand well.
hello sir,these were the errors generated when i tried to run the program…
1.Build path specifies execution environment JavaSE-1.6. There are no compatible JREs in the workspace.
2.The project cannot be built until build path errors are resolved
3.Unbound classpath container: ‘JRE System Library [JavaSE-1.6]‘ in project ‘First_hyberPro’
@Nandy
Seems you have different versions JDK,JRE’s, do one thing please uninstall java and reinstall (don’t let your java software update automatically).
Once you installed configure Eclipse normally(with default settings) and start your first example by following these steps.
http://www.java4s.com/hibernate/hibernate-hello-world-program-in-eclipse/
@java4s
It worked sir…thank you so much…
Hi sir,
explain hibernate tools with procedure(screen shots).
is it possible to develop hibernate application without configuration file?(pls provide example)
Sir I getting this error when running the application that Product.hbm.xml not found.
(no html)
@saptak
Make sure you have added Product.hbm.xml in your configuration file and in your application folder as well in appropriate position, download the application and check if you still have any issues.
Hi,
What is Hibernate N+1 problem. please give me answer with an example
@Vishal
Please ask your questions in our forum
hi Sir,
pls provide reverse engineering in hibernate?
Good explanation very precise..:)
@Java4s
Thanks a lot. very useful for freshers. As i m a beginner it helps me a lot… it helped me to make a first step in hibernate…
thanks.