How to connect hibernate with MySQL Database?


In this article, we will see how we can connect to MySQL database using an ORM (object relational mapping) framework like hibernate.

First of all, we need to add maven dependency for hibernate in our pom.xml file −

<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.6.2.Final</version> </dependency> Now, let us define an entity class that will be mapped to a database table using hibernate. @Entity @Table( name = " Employee") public class Employee { @Id @GeneratedValue(strategy = GenerationType.AUTO) Long id; @Column(name = "first_name") String firstName; @Column(name = "last_name") String lastName; //Getters //Setters }

In here,

@Table is used to specify the name of the table to which this class will be mapped.

@Entity will map the class to relational database table.

@Id will create a primary key on given attribute of the table.

@GeneratedValue specifies the strategy to be used for generating the values of the attribute. Strategy=GenerationType.AUTO means it will be auto-incremented.

Now, we need to define a configuration file for hibernate named hibernate.cfg.xml. This configuration file is to be used by hibernate to connect with the provided database.

<!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> <!-- JDBC Database connection settings --> <property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost:3306/dbName?useSSL=false</property> <property name="connection.username">root</property> <property name="connection.password">root</property> <!-- JDBC connection pool settings ... using built-in test pool --> <property name="connection.pool_size">1</property> <!-- Echo the SQL to stdout --> <property name="show_sql">true</property> <!-- Select our SQL dialect --> <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property> <!-- Drop and re-create the database schema on startup --> <property name="hbm2ddl.auto">create-drop</property> <!-- name of annotated entity class --> <mapping class="academy.company.Employee"/> </session-factory> </hibernate-configuration>

Session factory manages the creation and lifecycle of the session. We require a session factory per database.

Session is used to create a connection/session with the database.

Here, create-drop will check if the table is already present, then it will first drop the table and will create a new table.

Dialect represents the MySQL version that we are using in the database.

Example

Before we run our java application, we just need to configure sessionfactory in Main.java as −

package academy.company; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class Main { public static void main(String[] args) { SessionFactory sessionFactory; sessionFactory = new Configuration() .configure("academy/company/hibernate.cfg.xml") .buildSessionFactory(); } }

Now, when we start our java application we can see in the console that Hibernate will firstly drop the Employee table if it already exists. If not, it will create the Employee table with the attributes that we defined in our employee class.

Output

INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
Hibernate: drop table if exists Employee

Jan 08, 2022 1:26:32 PM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection

INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@eca6a74] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.

Hibernate: drop table if exists hibernate_sequence
Hibernate: create table Employee (id bigint not null, first_name varchar(255), last_name varchar(255), primary key (id)) engine=MyISAM

Updated on: 26-Aug-2022

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements