Tutorials Logic, IN +91 8092939553 info@tutorialslogic.com
FAQs Support
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Interview Questions Website Development
Compiler Tutorials

Hibernate Getting Started

Maven Dependencies

pom.xml - Hibernate Dependencies
<dependencies>
    <!-- Hibernate Core -->
    <dependency>
        <groupId>org.hibernate.orm</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>6.4.0.Final</version>
    </dependency>

    <!-- MySQL Connector -->
    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <version>8.2.0</version>
    </dependency>

    <!-- C3P0 Connection Pool (optional) -->
    <dependency>
        <groupId>org.hibernate.orm</groupId>
        <artifactId>hibernate-c3p0</artifactId>
        <version>6.4.0.Final</version>
    </dependency>
</dependencies>

hibernate.cfg.xml Configuration

hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <!-- Database connection -->
        <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mydb?useSSL=false</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">password</property>

        <!-- SQL Dialect -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

        <!-- Show generated SQL -->
        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.format_sql">true</property>

        <!-- Schema management: validate | update | create | create-drop -->
        <property name="hibernate.hbm2ddl.auto">update</property>

        <!-- Annotated entity classes -->
        <mapping class="com.example.entity.User"/>
        <mapping class="com.example.entity.Product"/>
        <mapping class="com.example.entity.Order"/>
    </session-factory>
</hibernate-configuration>

First Entity and SessionFactory

Entity Class and SessionFactory Setup
package com.example.entity;

import jakarta.persistence.*;

@Entity
@Table(name = "users")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "username", nullable = false, unique = true, length = 50)
    private String username;

    @Column(nullable = false)
    private String email;

    // No-arg constructor required by Hibernate
    public User() {}

    public User(String username, String email) {
        this.username = username;
        this.email    = email;
    }

    // Getters and setters
    public Long getId() { return id; }
    public String getUsername() { return username; }
    public void setUsername(String username) { this.username = username; }
    public String getEmail() { return email; }
    public void setEmail(String email) { this.email = email; }

    @Override
    public String toString() {
        return "User{id=" + id + ", username='" + username + "', email='" + email + "'}";
    }
}
package com.example.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
    private static final SessionFactory sessionFactory;

    static {
        try {
            // Load hibernate.cfg.xml from classpath
            sessionFactory = new Configuration()
                    .configure("hibernate.cfg.xml")
                    .buildSessionFactory();
        } catch (Exception e) {
            System.err.println("SessionFactory creation failed: " + e);
            throw new ExceptionInInitializerError(e);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static void shutdown() {
        getSessionFactory().close();
    }
}
package com.example;

import com.example.entity.User;
import com.example.util.HibernateUtil;
import org.hibernate.*;

public class Main {
    public static void main(String[] args) {
        // Save a user
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = session.beginTransaction();

        User user = new User("alice", "alice@example.com");
        session.persist(user); // INSERT INTO users ...

        tx.commit();
        session.close();
        System.out.println("Saved: " + user);

        // Retrieve the user
        session = HibernateUtil.getSessionFactory().openSession();
        User found = session.get(User.class, user.getId());
        System.out.println("Found: " + found);
        session.close();

        HibernateUtil.shutdown();
    }
}

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.