Advertisement

Google Ad Slot: content-top

HB Setting Up

~1 min read · Hibernate
On this page

Before using Hibernate, you need to install it, configure it with a database (MySQL/PostgreSQL), and set up the required configuration files.

Installing Hibernate with Maven:

To install Hibernate in a Maven project, add the following dependencies in your pom.xml file:

Maven Dependencies


pom.xml
org.hibernate hibernate-core 6.3.1.Final mysql mysql-connector-j 8.0.33 org.postgresql postgresql 42.5.4

Configuring Hibernate with MySQL/PostgreSQL:

Hibernate requires a configuration file to connect to the database. You can configure it using:

hibernate.cfg.xml (for Hibernate-based configuration)

Hibernate Configuration File: hibernate.cfg.xml

Example for MySQL:
com.mysql.cj.jdbc.Driver jdbc:mysql://localhost:3306/hibernatedb root org.hibernate.dialect.MySQLDialect update true true
Example for PostgreSQL:
org.postgresql.Driver jdbc:postgresql://localhost:5432/hibernatedb postgres password org.hibernate.dialect.PostgreSQLDialect update true

Hibernate Properties & Annotations:

Hibernate provides annotations for defining entity mappings, relationships, and constraints.

Student.java
import jakarta.persistence.*; @Entity // Marks this as a Hibernate Entity (table) @Table(name = "students") // Specifies table name public class Student { @Id // Primary Key @GeneratedValue(strategy = GenerationType.IDENTITY) // Auto-increment private Long id; @Column(name = "student_name", nullable = false) private String name; @Column(unique = true) private String email; // Constructors public Student() {} public Student(String name, String email) { this.name = name; this.email = email; } // Getters and Setters public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
Main.java
import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class Main { public static void main(String[] args) { // Create and save Student object Student student = new Student("John Doe", "john@example.com"); // Create Hibernate session SessionFactory sessionFactory = new Configuration().configure("hibernate.cfg.xml").addAnnotatedClass(Student.class).buildSessionFactory(); Session session = sessionFactory.openSession(); // Start transaction session.beginTransaction(); session.save(student); // Commit transaction session.getTransaction().commit(); // Close session session.close(); sessionFactory.close(); System.out.println("Hibernate setup successful!"); } }