Welcome to the Hibernate tutorial from beginner to advance. Hibernate is one of the most popular ORM tool. We will discuss each and every concept in detail. You will find this post very useful even you are beginner or advance in Hibernate.
We will understand the basic concept of Hibernate using the Hello World program that will be very simple hibernate program, will explain about hibernate concept.
Hello World Program
We will create the hello-world gradle based application. Project structure of this application is something like below.
Hibernate Properties
hibernate.cfg.xml
is a Hibernate configuration xml file which contain the required Hibernate
properties.
Most of the properties have their default properties. Some of the properties values need to have into this file,
so Hibernate use these properties to create connection with database.
<?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> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost:3306/helloworld?useSSL=false</property> <property name="connection.username">root</property> <property name="connection.password">santosh</property> <property name="hbm2ddl.auto">update</property> <!-- SQL Dialect --> <property name="dialect">org.hibernate.dialect.MariaDBDialect</property> <!--Echo all executed SQL query to console--> <property name="show_sql">true</property> <mapping resource="message.hbm.xml"/> </session-factory> </hibernate-configuration>
This table show some of the important properties that you will use into Hibernate configuration file.
Properties | Description |
---|---|
connection.driver_class | The JDBC driver class. |
connection.url | The JDBC URL to the database instance. |
connection.username | The database username to authenticate. |
connection.password | The database password to authenticate. |
hbm2ddl.auto | This property validates or exports schema DDL to the database when the SessionFactory is created. |
dialect | This property makes Hibernate to generate the appropriate SQL for the chosen database. |
show_sql | This property echo the generated SQL query on console. |
Hibernate Mapping File
Hibernate mapping file is used to map the object model to relational model. This mapping files instruct the Hibernate to map the defined class or classes to database table or tables.
Let's understand the mapping elements of the Hibernate mapping file.
Elements | Description |
---|---|
<hibernate-mapping> | This is a root element of the mapping file. which can contain all the <class> elements. |
<class> | This element is used to defined the Java class to Database table. |
<id> | This element maps the unique ID attribute in class to the primary key of the database table. |
<generator> | This element within the <id> element is used to generate the primary key values automatically. |
<property> | This element is used to map a Java class property to a column in the database table. |
We will cover the details of all other elements in separate post.
Create SessionFactory
Usually an application has a single SessionFactory
instance and threads servicing client requests
obtain Session
instances from this factory.
The internal state of a SessionFactory
is immutable. Once it is created this internal state is set.
This internal state includes all of the metadata about Object/Relational Mapping.
package com.walking.techie.utils; import org.hibernate.SessionFactory; import org.hibernate.boot.Metadata; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; public class HibernateUtil { public static final SessionFactory sessionFactory = buildSessionFactory(); private static SessionFactory buildSessionFactory() { try { StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder() .configure("hibernate.cfg.xml").build(); Metadata metadata = new MetadataSources(standardRegistry).getMetadataBuilder().build(); return metadata.getSessionFactoryBuilder().build(); } catch (Exception ex) { System.err.println("Initial session factory creation failed: " + ex.getMessage()); throw new ExceptionInInitializerError(); } } public static SessionFactory getSessionFactory() { return sessionFactory; } }
Model
Message
Java class is a persistence entity that will save into relational database. I have used the
lombok annotation here to create getter, setter, default constructor of the Message class.
package com.walking.techie.model; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor public class Message { private Long id; private String message; public Message(String message) { this.message = message; } }
HelloWorldClient
This class main method will save the message object into MESSAGE table of helloworld database.
package com.walking.techie; import com.walking.techie.model.Message; import com.walking.techie.utils.HibernateUtil; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; public class HelloWorldClient { public static void main(String[] args) { // get session factory of an application SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); // Open a session Session session = sessionFactory.openSession(); // Begin a unit of work and return the associated Transaction object. Transaction transaction = session.beginTransaction(); Message message = new Message("Hello world with Hibernate"); // save the message object into table session.save(message); // commit the transaction transaction.commit(); // End the session by releasing the JDBC connection and cleaning up. session.close(); } }
Before running this application you need to create the helloworld database into MySQL. Table will created automatically because we have set the hbm2ddl.auto to update.
Output
This application will save the message object in MESSAGE table.
output in console
Jan 13, 2018 6:51:39 PM org.hibernate.Version logVersion INFO: HHH000412: Hibernate Core {5.2.12.Final} Jan 13, 2018 6:51:39 PM org.hibernate.cfg.Environment <clinit> INFO: HHH000206: hibernate.properties not found Jan 13, 2018 6:51:40 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit> INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final} Jan 13, 2018 6:51:41 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!) Jan 13, 2018 6:51:41 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator INFO: HHH10001005: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/helloworld?useSSL=false] Jan 13, 2018 6:51:41 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator INFO: HHH10001001: Connection properties: {user=root, password=****} Jan 13, 2018 6:51:41 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator INFO: HHH10001003: Autocommit mode: false Jan 13, 2018 6:51:41 PM org.hibernate.engine.jdbc.connections.internal.PooledConnections <init> INFO: HHH000115: Hibernate connection pool size: 20 (min=1) Jan 13, 2018 6:51:42 PM org.hibernate.dialect.Dialect <init> INFO: HHH000400: Using dialect: org.hibernate.dialect.MariaDBDialect Jan 13, 2018 6:51:42 PM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@2b58f754] 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: create table MESSAGE (ID bigint not null, MESSAGE varchar(255), primary key (ID)) engine=InnoDB Hibernate: select max(ID) from MESSAGE Hibernate: insert into MESSAGE (MESSAGE, ID) values (?, ?)
No comments :
Post a Comment