Hibernate is an Object Relational Mapping (ORM) tool for Java. It provides a framework for mapping an object-oriented domain model to a relational database, such as MySQL.
Configuration
Note: The mapping used here avoids using annotations in the Java class.
Instead, we will create a mapping file for the class object, under the same package.
The project structure under src/main/java/merikanto
is below :
1 2 3 4 5 6 7 HelloHibernate/src/main/java/merikanto └── hibernate ├── entity │ ├── User.hbm.xml │ └── User.java └── test └── Test.java
To start with, we first set the configs below in MySQL:
1 2 3 > create database hibernate;> SET GLOBAL time_zone = '-4:00' ;
Then create a Maven project in terminal:
1 2 3 4 mvn archetype:generate \ -DgroupId=merikanto.hibernate \ -DartifactId=HelloHibernate \ -DarchetypeArtifactId=maven-archetype-quickstart
Open the project in Intellij, and make sure that the database is connected (Need MySQL connector).
Project structure - Libraries - search mysql - connect
View - Tool windows - database - add data source - mysql
Next, edit pom.xml
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 <?xml version="1.0" encoding="UTF-8"?> <project xmlns ="http://maven.apache.org/POM/4.0.0" xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation ="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" > <modelVersion > 4.0.0</modelVersion > <groupId > merikanto.hibernate</groupId > <artifactId > HelloHibernate</artifactId > <version > 1.0-SNAPSHOT</version > <name > HelloHibernate</name > <url > https://merikanto.github.io</url > <properties > <project.build.sourceEncoding > UTF-8</project.build.sourceEncoding > <maven.compiler.source > 1.8</maven.compiler.source > <maven.compiler.target > 1.8</maven.compiler.target > </properties > <dependencies > <dependency > <groupId > org.hibernate</groupId > <artifactId > hibernate-core</artifactId > <version > 5.4.11.Final</version > </dependency > <dependency > <groupId > mysql</groupId > <artifactId > mysql-connector-java</artifactId > <version > 8.0.19</version > </dependency > </dependencies > <build > <resources > <resource > <directory > src/main/java</directory > <includes > <include > **/*.xml</include > </includes > </resource > </resources > <plugins > <plugin > <groupId > merikanto.hibernate</groupId > <artifactId > HelloHibernate</artifactId > <version > 1.0-SNAPSHOT</version > <configuration > <classpathScope > test</classpathScope > <mainClass > Test</mainClass > </configuration > </plugin > </plugins > </build > </project >
Create package entity
under merikanto.hibernate
, then create new object (class) User
under entity
.
A user has 3 properties:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 package merikanto.hibernate.entity;public class User { private int id; private String username; private String password; public int getId () { return id; } public void setId (int id) { this .id = id; } public String getUsername () { return username; } public void setUsername (String username) { this .username = username; } public String getPassword () { return password; } public void setPassword (String password) { this .password = password; } }
Then create User.hbm.xml
, under the same entity
package as User
class.
This file is for mapping (One object – One mapping file).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <?xml version="1.0"?> <hibernate-mapping package ="merikanto.hibernate.entity" > <class name ="User" table ="user_info" > <id name ="id" column ="user_id" /> <property name ="username" column ="user_username" > </property > <property name ="password" column ="user_password" > </property > </class > </hibernate-mapping >
Under src/main/java
, create Hibernate configuration file hibernate.cfg.xml
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 <?xml version='1.0' encoding='utf-8'?> <hibernate-configuration > <session-factory > <property name ="connection.driver_class" > com.mysql.jdbc.Driver</property > <property name ="connection.url" > jdbc:mysql://localhost:3306/hibernate</property > <property name ="connection.username" > root</property > <property name ="connection.password" > </property > <property name ="dialect" > org.hibernate.dialect.MySQL8Dialect</property > <property name ="show_sql" > true</property > <property name ="format_sql" > true</property > <property name ="hbm2ddl.auto" > update</property > <mapping resource ="merikanto/hibernate/entity/User.hbm.xml" /> </session-factory > </hibernate-configuration >
And now the configuration is done.
Test (CRUD) Now we run some tests for hibernate. There will be four tests, focusing on the operations below:
Create
Read (search)
Update
Delete
Create First we create package test
under merikanto.hibernate
, then we create class Test
under merikanto.hibernate.test
.
The first test is for the Create
operation.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 package merikanto.hibernate.test;import merikanto.hibernate.entity.User;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;public class Test { public static void main (String[] args) { Configuration configuration = new Configuration().configure(); @SuppressWarnings("deprecation") SessionFactory sessionFactory = configuration.buildSessionFactory(); Session session = sessionFactory.openSession(); session.beginTransaction(); User user = new User(); user.setId(1 ); user.setUsername("admin" ); user.setPassword("admin" ); session.save(user); session.getTransaction().commit(); session.close(); sessionFactory.close(); } }
Then run it in Terminal:
1 2 mvn compile mvn exec:java -Dexec.mainClass="merikanto.hibernate.test.Test"
Read The second test is for the Read
operation.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 package merikanto.hibernate.test;import merikanto.hibernate.entity.User;import java.util.List;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.boot.MetadataSources;import org.hibernate.boot.registry.StandardServiceRegistry;import org.hibernate.boot.registry.StandardServiceRegistryBuilder;import org.hibernate.query.Query;public class Test { public static void main (String[] args) { StandardServiceRegistry registry = new StandardServiceRegistryBuilder() .configure("hibernate.cfg.xml" ) .build(); SessionFactory sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory(); Session session = sessionFactory.openSession(); session.beginTransaction(); StringBuilder hq = new StringBuilder(); hq.append("from " ).append( User.class.getName() ); Query query = session.createQuery( hq.toString() ); List<User> users = query.list(); for (User user : users) { System.out.println( user.getUsername() ); } session.getTransaction().commit(); session.close(); sessionFactory.close(); } }
Then run it in Terminal:
1 2 mvn compile mvn exec:java -Dexec.mainClass="merikanto.hibernate.test.Test"
Update The third test is for the Update
operation.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 package merikanto.hibernate.test;import merikanto.hibernate.entity.User;import java.util.List;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.boot.MetadataSources;import org.hibernate.boot.registry.StandardServiceRegistry;import org.hibernate.boot.registry.StandardServiceRegistryBuilder;import org.hibernate.query.Query;public class Test { public static void main (String[] args) { StandardServiceRegistry registry = new StandardServiceRegistryBuilder() .configure("hibernate.cfg.xml" ) .build(); SessionFactory sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory(); Session session = sessionFactory.openSession(); session.beginTransaction(); StringBuilder hq = new StringBuilder(); hq.append("from " ).append(User.class.getName()).append(" where user_username=:name" ); Query query = session.createQuery(hq.toString()); query.setParameter("name" ,"user1" ); List<User> users = query.list(); for (User user : users) { user.setPassword("123-user" ); session.update(user); } session.getTransaction().commit(); session.close(); sessionFactory.close(); } }
Then run it in Terminal:
1 2 mvn compile mvn exec:java -Dexec.mainClass="merikanto.hibernate.test.Test"
Delete The fourth test is for the Delete
operation.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 package merikanto.test.hibernate.test;import merikanto.hibernate.entity.User;import java.util.List;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.boot.MetadataSources;import org.hibernate.boot.registry.StandardServiceRegistry;import org.hibernate.boot.registry.StandardServiceRegistryBuilder;import org.hibernate.query.Query;public class Test { public static void main (String[] args) { StandardServiceRegistry registry = new StandardServiceRegistryBuilder() .configure("hibernate.cfg.xml" ) .build(); SessionFactory sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory(); Session session = sessionFactory.openSession(); session.beginTransaction(); StringBuilder hq = new StringBuilder(); hq.append("from " ).append(User.class.getName()).append(" where user_username=:name" ); Query query = session.createQuery(hq.toString()); query.setParameter("name" , "user1" ); List<User> users = query.list(); for (User user : users) { session.delete(user); } session.getTransaction().commit(); session.close(); sessionFactory.close(); } }
Then run it in Terminal:
1 2 mvn compile mvn exec:java -Dexec.mainClass="merikanto.hibernate.test.Test"
And we now have implemented the tests.