Hibernate Tutorial «Prev  Next»

Preparing Hibernate Database

To prepare a MySQL database for use with Hibernate ORM 6.6, follow these steps:
  1. Install MySQL and Create a Database
    • Ensure MySQL is installed and running.
    • Create a database for your Hibernate application:
    • CREATE DATABASE my_hibernate_db CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
      
    • This ensures proper Unicode support.
  2. Create a Database User and Grant Privileges
    • Create a user for Hibernate to connect with and grant appropriate privileges:
    • CREATE USER 'hibernate_user'@'localhost' IDENTIFIED BY 'secure_password';
      GRANT ALL PRIVILEGES ON my_hibernate_db.* TO 'hibernate_user'@'localhost';
      FLUSH PRIVILEGES;
      
    • For production, grant only necessary privileges like `SELECT`, `INSERT`, `UPDATE`, and `DELETE`.
  3. Configure MySQL JDBC Driver Dependency
    • For Maven:
    • <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-j</artifactId>
          <version>8.0.33</version>
      </dependency>
      
    • For Gradle:
    • dependencies {
          implementation 'mysql:mysql-connector-j:8.0.33'
      }
      
    • Ensure you use MySQL Connector/J version 8.x or later, which is compatible with Hibernate 6.
  4. Configure Hibernate in `hibernate.cfg.xml`
    • Create or modify `hibernate.cfg.xml` with MySQL-specific settings:
      <hibernate-configuration>
          <session-factory>
              <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
              <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/my_hibernate_db?useSSL=false&serverTimezone=UTC</property>
              <property name="hibernate.connection.username">hibernate_user</property>
              <property name="hibernate.connection.password">secure_password</property>
      
              <!-- Hibernate Dialect -->
              <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
      
              <!-- Hibernate Connection Pooling -->
              <property name="hibernate.hikari.minimumIdle">5</property>
              <property name="hibernate.hikari.maximumPoolSize">20</property>
              
              <!-- Hibernate Schema Management -->
              <property name="hibernate.hbm2ddl.auto">update</property>
      
              <!-- Hibernate Logging -->
              <property name="hibernate.show_sql">true</property>
              <property name="hibernate.format_sql">true</property>
          </session-factory>
      </hibernate-configuration>
      
      
    • `hibernate.dialect`: Hibernate 6 has specific dialects for MySQL. It automatically detects the version, but explicitly setting it may be necessary.

  5. Use the Correct Hibernate Dialect
    • Hibernate 6.6 supports multiple MySQL dialects:
    • For MySQL 8+:
    • org.hibernate.dialect.MySQLDialect
      
    • For MySQL 5.7 or lower:

    • org.hibernate.dialect.MySQL5Dialect
      
  6. Set Up Entity Classes
    • Ensure your entity classes are properly annotated:
      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)
         private String username;
      
         @Column(name = "email", nullable = false)
         private String email;
      
         // Getters and Setters
      }
      
  7. Optimize MySQL Settings for Hibernate
    • To improve Hibernate’s performance with MySQL, update `my.cnf` (or `my.ini` on Windows):
    • [mysqld]
      max_connections = 200
      innodb_buffer_pool_size = 512M
      innodb_log_file_size = 128M
      innodb_flush_log_at_trx_commit = 1
      
    • Increase connection limits if running in production.
    • Adjust buffer pool size for better query performance.
  8. Test Database Connection
    • Run a basic test to ensure Hibernate can connect to MySQL:
    • SessionFactory sessionFactory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
      Session session = sessionFactory.openSession();
      session.close();
      
  9. Deploy and Monitor
    • Enable Hibernate SQL logging for debugging:
    • hibernate.show_sql=true
      hibernate.format_sql=true
      
    • Use Flyway or Liquibase for schema migrations in production.

By following these steps, your MySQL database will be well-prepared for use with Hibernate ORM 6.6.
Let us consider a simple database schema with a singe table as USER.
CREATE  TABLE `user` (USER_ID` int(11) NOT NULL default  '0',
`USER_NAME` varchar(255) NOT NULL  default '',
`USER_PASSWORD` varchar(255) NOT NULL  default '',
`USER_FIRST_NAME` varchar(255) default  NULL,
`USER_LAST_NAME` varchar(255) default  NULL,
`USER_EMAIL` varchar(255) default  NULL,
`USER_CREATION_DATE` date default  NULL,
`USER_MODIFICATION_DATE` date default  NULL,
PRIMARY KEY (`USER_ID`),
UNIQUE KEY `USER_NAME` (`USER_NAME`)
) ;