Book.java
Now, i am going to create a simple POJO class Book.java with some properties and their setters and getters.
package com.bloggers.model; import java.util.Date; public class Book { /* for primary key in database table */ private int bookId; private String bookName; private Date date; public int getBookId() { return bookId; } public void setBookId(int bookId) { this.bookId = bookId; } public String getBookName() { return bookName; } public void setBookName(String bookName) { this.bookName = bookName; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } }
Few point while creating a model object or JavaBeans (Book.java) class.
Now second step is we have to create a hbm file with extension .hbm.xml. HBM file means Hibernate Mapping File. Mapping file gives all the information to hibernate about table columns etc which are mapped to object.
All persistent entity classes need a mapping to a table in the SQL database.
Basic structor of hbm file
<hibernate -mapping="-mapping"> [...] </hibernate>
Note:
I will complete this step by step and try to explain all the elements.
1. Add a class element between two hibernate-mapping tags.
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.bloggers.model.Book" > </class> </hibernate-mapping>
class=”com.bloggers.model.Book” .Specify the qualified class name in name attribute of class element.
2. Next, we need to tell Hibernate about the remaining entity class properties. By default, no properties of the class are considered persistent.
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.bloggers.model.Book" > <id name="bookId"/> <property name="date" column="PUBLISH_DATE"/> </class> </hibernate-mapping>
name=”bookId” attribute of the property element tells Hibernate which getter and setter methods to use in our case hibernate will search for getBookId() , setBookId() etc methods.
Question : Why does the date property mapping include the column attribute, but the bookID does not?
Answer : Without the column attribute, Hibernate by default uses the property name as the column name. This works for bookId, however, date is a reserved keyword in most databases so you will need to map it to a different name.
Hibernate required a configuration file for making the connection with database by default the file name is hibernate.cfg.xml
We can do hibernate configuration in 3 different ways and these are :-
I am going to use the 2 option means by using hibernate.cfg.xml file.
<?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> <!-- Database connection settings --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost:3306/hibernatedb</property> <property name="connection.username">root</property> <property name="connection.password">root</property> <!-- JDBC connection pool (use the built-in) --> <property name="connection.pool_size">1</property> <!-- SQL dialect --> <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property> <!-- Disable the second-level cache --> <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property> <!-- Echo all executed SQL to stdout --> <property name="show_sql">true</property> <!-- Drop and re-create the database schema on startup --> <property name="hbm2ddl.auto">create</property> <mapping resource="com/bloggers/model/Book.hbm.xml"/> </session-factory> </hibernate-configuration>
HibernateUtil.java
Utility class for getting the sessionFactory.
package com.bloggers.util; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtil { private static final SessionFactory sessionFactory = buildSessionFactory(); private static SessionFactory buildSessionFactory() { try { // Create the SessionFactory from hibernate.cfg.xml return new Configuration().configure().buildSessionFactory(); } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; } }
Run the example
Create a simple class for running the example.
package com.bloggers; import java.util.Date; import org.hibernate.Session; import org.hibernate.SessionFactory; import com.bloggers.model.Book; import com.bloggers.util.HibernateUtil; public class HibernateTest { public static void main(String[] args) { HibernateTest hibernateTest = new HibernateTest(); /* creating a new book object */ Book book = new Book(); book.setBookId(1); book.setDate(new Date()); book.setBookName("Hibernate in action"); /* saving the book object */ hibernateTest.saveBook(book); } public void saveBook(Book book) { SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); Session session = sessionFactory.openSession(); session.beginTransaction(); /* saving the book object here */ session.save(book); session.getTransaction().commit(); } }
Before running the HibernateTest class make sure you have created a schema named hibernatedb in MySQL database .
Question : Why schema named hibernatedb ?
Answer : Because in hibenate.cfg.xml
<property name=”connection.url”>jdbc:mysql://localhost:3306/hibernatedb</property>
we have specify hibernatedb. You are free to change whatever name you want. Create schema using mysql>create schema hibernate; command.
Question : Did you see the table it does not contains the column name bookName?
Answer : If yes then you can easily found that why we do not have bookName in table book and the answer is because we did not map the bookName property in our hbm file so map the property and run the main method again and you will observe that.
Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…
Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…
Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…
Technology has emerged a lot in the last decade, and now we have artificial intelligence;…
Managing a database is becoming increasingly complex now due to the vast amount of data…
Overview In this article, we will explore Spring Scheduler how we could use it by…