Newsletter |
Hibernate Hello World Program (Hibernate Insert Query)
Mates, here 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 here, 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
You Might Also Like
::. About the Author .:: | ||
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.
https://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.
Good tutorial 🙂
Nice one, very good. Thanks a lot this article. It helped me a lot.
Thanks very simple example easy to understand
Hai , Thanks a lot . it helped me to make a first step in hibernate…
Hello sir ,i am Sachin and fresher in java.I learned PHP.and i thought that JAVA is a tough language.But when i visited your site i promise myself that i will definately learn java from Here.
Thanks a lot for such a wonderful tutorials..:)
Hi thank you so much….i learnt a lot from this site..
Wow…!!! it’s really grate….very very helpfull thanks a lot….
Please tell me how to use data source in hibernate.
i got this program…… really good…thank you………
Hello Sir,
I am beginner in Hibernate Frame work. I want to create Mysql Database Schema (new database) automatically. But its not working showing error that unknown database. How to solved this problem.
I use create/update that work only for table creation/update.
How to create new DB Schema rather than new table ?
hello sir what is singleton design pattern when will we use in project give me any real time example???
Hello Sir,
My I know the high level program of hibernate which we used in all real time applications commonly.
thanks in Advance..but please give me reply either by mail Id or as a reply to this comment
hi,am new to the practise in eclipse,i follow your steps whatever you mentioned in this blog.am getting the below error.tell me the reasons & steps come out for this problem
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Exception in thread “main” org.hibernate.HibernateException: hibernate.cfg.xml not found
at org.hibernate.util.ConfigHelper.getResourceAsStream(ConfigHelper.java:147)
at org.hibernate.cfg.Configuration.getConfigurationInputStream(Configuration.java:1405)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1427)
at str.Client.main(Client.java:11)
It works perfectly. Thanks alot.
Very nice tutorial.
For boilderplate code, we move to spring framework.
To manage the classpath for 12 jar files, we move to eclipse.
May be to move to maven for managing the dependency graph of jars?
–
When did we started down this path of covering up engineer’s ignorance, lazyness, resistence to learn fundamentals with increasingly bigger and complex frameworks?
–
Factories, sessions, … Every new question you get with plain SQL, JDBC, now needs to be rephrased, reanswered. For ex., what do I do if I have the table with same name but my application’s runtime configuration is going to decide if I am going to store the object in Oracle or DB2? I know, there is an answer for it. But, is it obvious? It needs to be understood now in “Hibernate’s Lingo”.
–
In order to move a mosquito, now we are proposing a nuclear factory
–
if i run my project it may show a hibernate which is referenced by a class path does not exist error
Hi , i am getting below error while running my code..
Can anyone please help me in this..
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Exception in thread “main” org.hibernate.HibernateException: Could not parse configuration: hibernate.cfg.xml
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1491)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1425)
at barclays.org.logic.InsertData.main(InsertData.java:15)
Caused by: org.dom4j.DocumentException: hibernate.sourceforge.net Nested exception: hibernate.sourceforge.net
at org.dom4j.io.SAXReader.read(SAXReader.java:484)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1481)
… 2 more
Do changes in product.hbm.xml as follows:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping package="com.mobicule">
<class name = "Product" table = "PRODUCTT" >
<id name = "proId" column = "pid">
<generator class="assigned" />
</id>
<property name = "proNm" column = "pnm" />
<property name = "price" />
</class>
</hibernate-mapping>
enter package name in mapping file
<hibernate-mapping package="Enter your pojo class package name here">
tutorial is good but you explained how to save one object only,
but i want to know multiple objects at a time with what we give input with key board at runtime….
This site is too useful. contents are so simple to understand.
Thanks,
Nandha kumar C
I know 12 jar files require for hibernate… but i don’t know how to set jar files in eclipse can you please help me…
After long day of tried in eclipse,finally ran in Netbeans. thx lot.
Please help me,
when I run in apache tomcat folder
javax.servlet.ServletException: java.lang.NoClassDefFoundError: org/dom4j/DocumentException
org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:911)
org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:840)
org.apache.jsp.hibernateexample_jsp._jspService(hibernateexample_jsp.java:103)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
Hello sir,
I am beginner. How can I provide a message data store in database or not. How to conform data store in database. In jdbc return 0 or 1 to know data save successfully.
Java4s is the best tutorial,
I got good knowledge in hibernate through the java4s.
Hi,
I started to learn hibernate and am when am trying this sample program, object is not saved in database. session.save(object) is not working. Can anyone help me. Connection has happened table is created but object is not saved. How to solve this problem.
Hi,
It Should Be instead of (Line no. 19 of hibernate.cfg.xml).
very good tutorial.but require NEXT button on website.
Awesome tutorials easy to understand.
Hi sir,
my question is??
what is the difference between satatic and transient in the process of serilization ,i want difference between them….
Hi ,
This is very good site for beginners.Thanks a lot for your valueable time.
in above program,hibernate.cfg.xml file u have mentioned dialet instead of dialect due to which getting error “Hibernate Dialect must be explicitly set”
org.hibernate.dialect.OracleDialect
Hi java4s team,
I executed program in eclipse but i got one exception. The exception i mention bellow.
Exception in thread “main” org.hibernate.HibernateException: Could not parse configuration: hibernate.cfg.xml
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1491)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1425)
at san.StoreData.main(StoreData.java:18)
Caused by: org.dom4j.DocumentException: Error on line 3 of document : The document type declaration for root element type “hibernate-configuration” must end with ‘>’. Nested exception: The document type declaration for root element type “hibernate-configuration” must end with ‘>’.
at org.dom4j.io.SAXReader.read(SAXReader.java:482)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1481)
… 2 more
Please give me replay as soon as possible.
thank you
Hello Sir,
I have loaded the postgres driver for my Hibernate application but not able to connect to Database it is showing following error ,please help me..
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" org.hibernate.exception.JDBCConnectionException: Cannot open connection
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:74)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
Could not find or load main class antlr.debug.misc.ASTFrame
Those who got the error like :
(
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Exception in thread “main” org.hibernate.HibernateException: Could not parse configuration: hibernate.cfg.xml
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1491)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1425)
at barclays.org.logic.InsertData.main(InsertData.java:15)
Caused by: org.dom4j.DocumentException: hibernate.sourceforge.net Nested exception: hibernate.sourceforge.net
at org.dom4j.io.SAXReader.read(SAXReader.java:484)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1481)
… 2 more
)
try this change as follows ..Then it will run fine..:==
do change in your product.hbm.xml as below:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.mobicule">
<class name = "Product" table = "PRODUCTT" >
<id name = "proId" column = "pid">
<generator class="assigned" />
</id>
<property name = "proNm" column = "pnm" />
<property name = "price" />
</class>
</hibernate-mapping>
it's Great site to learn .
Its really helpful Sir.
Thank you
Hi Brother.
Thank you for your Guidance on Hibernate. Every character here and previous Site page is precious, descriptive, very good.
You are one good person to openly share such amazing instances.
Thank you.
Hi,
Can u help on this issue,how we will get the sessionfactiory in hibernate5,without changing of hibernate3 code.
Why we use the tag session-factory in hibernate configuration file ?
Hi ,
I am getting the below error,while running the java Application.
Error: Could not find or load main class com…