java hibernate example

Step 1: Create a Maven Project and add below dependencies into pom file,
this pom file will install all the dependency that required to work with Mysql and herbernate

	<!-- -->
	<!-- -->

Step 2: Add/Install JBoss plugin using Eclipse, To do it go into this menu location below
Eclipse-> Help -> Eclipse Marketplace

Step 3: Create an hibernate.cfg.xml file into project directory
File name: hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
		"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.password">rootpassword</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/dbtest</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <!-- create/update table operation into db  -->
        <property name="">update</property>

Step 4: Create an Entity class Alien.Java

import javax.persistence.Entity;
import javax.persistence.Id;

public class Alien {

	private int aid;
	private String aname;
	private String color;

	public int getAid() {
		return aid;
	public void setAid(int aid) {
		this.aid = aid;
	public String getAname() {
		return aname;
	public void setAname(String aname) {
		this.aname = aname;
	public String getColor() {
		return color;
	public void setColor(String color) {
		this.color = color;

Step 4: Add below code into your desire function

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

 * Database
public class App 
    public static void main( String[] args )
        Alien alien = new Alien();
        Configuration con = new Configuration().configure().addAnnotatedClass(Alien.class);
        ServiceRegistry registry = new ServiceRegistryBuilder()
        SessionFactory sf = con.buildSessionFactory(registry);
        Session session = sf.openSession();
        Transaction tx = session.beginTransaction();

You May Also Like

About the Author: Jafor Iqbal

Leave a Reply