Hibernate Hello World Example
In this article, we will use Hibernate to connect to a MySQL database, writes a record to a table and then retrieve it.
For this, first lets add the required Hibernate dependencies and MySQL driver JAR file to the project.
You can refer the following article for this :
Hibernate Setup for Java project
Once the setup is complete, create a POJO corresponding to the table that we plan to create in the database.
Employee POJO
We are planning to create an Employee table and add some data to it. So, lets create an Employee class with the annotations as provided below.
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 | package com.topjavatutorial; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class Employee { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @Column private String name; @Column private int age; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String toString() { return "Employee{id = " + getId() + ", name = " + getName() + ", age = " + getAge() + "}"; } } |
In the above example, we are using annotations to map the POJO elements to the corresponding table attributes.
@Entity annotation maps the Employee POJO to corresponding table in database.
The attribute is marked with @Id annotation. It is also marked with a @GeneratedValue annotation that specifies how this identifier values will be
generated. Identity generation relies on natural table sequencing. The other available generation options are : sequence, table, auto and none.
@Column annotation is used to identify an attribute as a column of the table.
Hibernate configuration file
Hibernate provides a configuration hibernate.cfg.xml that will be store the database configurations for hibernate.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory name=""> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.password">password</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/TestDB</property> <property name="hibernate.connection.username">userid</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hibernate.show_sql">true</property> <property name="hibernate.format_sql">true</property> <property name="hibernate.hbm2ddl.auto">create</property> <mapping class="com.topjavatutorial.Employee"/> </session-factory> </hibernate-configuration> |
The configuration file hibernate.cfg.xml contains the JDBC driver class, JDBC URL and userid/password to access the database.
We also specify a dialect that allows Hibernate to correctly produce SQL for each given database.
show_sql is used to determine if you want to dump the generated SQL to console.
hbm2ddl.auto specifies what to do with the schema.In this case, we specify the schema to created on startup.
Lastly, we specify the class that should be managed.. in this example, we specify the Employee class.
Utility class for getting a Session
In Hibernate, we need a Session object to interact with the database.
We obtain the Session in following steps :
– Create a Hibernate Configuration object that references the xml configuration file.
– Build a SessionFactory object from the Configuration object.
– Retrieve the Hibernate Session objects from SessionFactory.
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 | package com.topjavatutorial; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder; public class HibernateSessionUtil { private static HibernateSessionUtil instance = new HibernateSessionUtil(); private static SessionFactory factory; private HibernateSessionUtil() { Configuration configuration = new Configuration(); configuration.configure("hibernate.cfg.xml"); factory = configuration.buildSessionFactory(); } public static Session getSession() { return getInstance().factory.openSession(); } public static HibernateSessionUtil getInstance() { return instance; } } |
Creating an Employee record in database and reading it
Now, lets create a Main class and add methods to read/write Employee data using the Hibernate Session object.
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 | package com.topjavatutorial; import java.util.List; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; public class HibernateHelloWorld { SessionFactory factory; public static void main(String[] args) { Session session = HibernateSessionUtil.getSession(); saveEmployee(session); getEmployee(session); session.close(); } public static void saveEmployee(Session session) { Employee employee = new Employee(); employee.setName("John Doe"); employee.setAge(30); Transaction trn = session.beginTransaction(); session.persist(employee); trn.commit(); } public static void getEmployee(Session session) { List<Employee> emplList = session.createQuery("from Employee").list(); for (Employee emp : emplList) System.out.println(emp); } } |
Running the above program will produce the following output :
Employee{id = 1, name = John Doe, age = 30}
© 2016, www.topjavatutorial.com. All rights reserved. On republishing this post, you must provide link to original post