Newsletter

Hibernate Hello World Program With Annotations

Hibernate » on Aug 30, 2011 { 13 Comments } By Sivateja

Folks we will see one simple program with hibernate annotations, let us take inserting a record [ saving one object ] into the database application.  And remember in the annotations no need to write mapping xml, hope you remember the previous sessions 🙂

Files required..

  • Product.java [ our pojo class ]
  • ClientForSave.java
  • hibernate.cfg.xml

Product.java

package str;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "student_talbe")
public class Product{

	@Id
	@Column(name="proid")
	private int productId;

	@Column(name="proName", length=10)
	private String proName;

	@Column(name="price")
	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;
	}
}

ClientForSave.java

package str;

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

public class ClientForSave { 

    public static void main(String[] args)
    {

        AnnotationConfiguration cfg=new AnnotationConfiguration();
        cfg.configure("hibernate.cfg.xml");

        SessionFactory factory = cfg.buildSessionFactory();
        Session session = factory.openSession();
        Product p=new Product(); 

        p.setProductId(105);
        p.setProName("java4s");
        p.setPrice(15000);

        Transaction tx = session.beginTransaction();
        session.save(p);
        System.out.println("Object saved successfully using annotations.....!!");
        tx.commit();
        session.close();
        factory.close();
    }

}

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>
<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.username">system</property>
<property name="connection.password">admin</property>

<property name="dialect">org.hibernate.dialect.OracleDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>

<mapping class="str.Product" />

</session-factory>
</hibernate-configuration>

And friends,  no need to explain there i think.  Please refer previous introduction sessions on annotations in case  you have any doubt.

Output

​​

You Might Also Like

  ::. About the Author .::

Java4s_Author
Sivateja Kandula - Java/J2EE Full Stack Developer
Founder of Java4s - Get It Yourself, A popular Java/J2EE Programming Blog, Love Java and UI frameworks.
You can sign-up for the Email Newsletter for your daily dose of Java tutorials.

Comments

13 Responses to “Hibernate Hello World Program With Annotations”
  1. Mohammed Vaseem says:

    Hello Java4s,
    Am getting exception in this program.
    Showing exception as
    Exception in thread “main” org.hibernate.MappingException: Unknown entity: str.Product

    Please help!

  2. Mohammed Vaseem says:

    I got solution for the exception which i was facing.

    Exception in thread “main” org.hibernate.MappingException: Unknown entity: str.Product

    If we add the two lines in the hibernate.cfg file then i did not got that exception again and the program got executed successfully..

  3. Java4s says:

    @Vaseem

    Hmm… str.Product !
    Vaseem what are those 2 lines you added into hibernate.cfg ?

  4. Mohammed Vaseem says:

    The program can get executed even with one line..
    that line is..

    When we are not using hbm.xml file(mapping file), then we have to give fully qualified name of the annotated class to the mapping element.

  5. Ambresh Sharna says:

    i need some more emphasis on NamedQuery theory and Example like as development mode i can use that..if you can do… would b better for me…Thanks Java4s

  6. Aalam says:

    In the hibernate.cfg.xml file there is no mapping for pojo class…we need to map the pojo class as we are not using hbm.xml

  7. Java4s says:

    @Aalam

    Yeah in the 18th line, we must specify the mapping class name you are correct, that should be class=”str.Product”. Corrected..!!

    Thanks Aalam 🙂

  8. stephen says:

    Db table name : student_table
    Table name mentioned as @Table(name = “student_talbe”)

    table name mentioned in are differnt. How will this program work ? 🙁

  9. To stephen: Hi Stephen,Hibernate will create table automatically as per given query in “update” in hibernate.cfg.xml file.Here you can also use “create” instead of update.

  10. Govardhan MK says:

    Sir as you said we use annaotations to avoid using mapping xml i.e instead of using mapping xml we r using annotations.

    My question is in your herbernate.cfg.xml file Why you are again using
    ?????

    please answer me!!!!!!

  11. Raja says:

    Hi,Java4s i have a solution for Hibernate Mapping Exception

    Solution is:

    Just set in your client class 15th line

    cfg.addAnnotatedClass(Product.class);

    No need to set any
    <mapping class="str.Product"/> in your configrtation FIle

  12. Anuj says:

    To Execute above program.
    We need to create table in data base or not ?

  13. PRAKASH SINGH KARMYAL says:

    Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/log4j/LogManager
    i use hibernet 5 and jdk 8

Name*
Mail*
Website



By posting your answer, you agree to our comments policy.
Most Recent Posts from Top Categories
Spring Boot Hibernate Spring
Contact | About Us | Privacy Policy | Advertise With Us

© 2010 - 2024 Java4s - Get It Yourself.
The content is copyrighted to Sivateja Kandula and may not be reproduced on other websites.