MySQL / MariaDb + Hibernate Annotation Configuration Example
Maven Dependencies
We are using Apache Maven to manage the projects dependencies. Add the following dependencies to your projects pom.xml file. The database driver mysql-connector-java is required and works for MySQL and MariaDB databases.
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>6.0.4</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.2.3.Final</version> </dependency>
Project Structure
Make sure the Hibernate.cfg.xml resides on the classpath in the src/main/resources folder.
src | +--main | +--java | +--com | +--memorynotfound | +--hibernate | |--App.java | |--Book.java | |--HibernateUtil.java | +--resources | |--Hibernate.cfg.xml pom.xml
Model Class + Hibernate Annotations
We demonstrate the hibernate Annotation configuration by inserting a simple POJO into the database. As you can see, the following POJO has plain java properties. The properties are enhanced with java persistence annotations.
package com.memorynotfound.hibernate; import javax.persistence.*; import java.io.Serializable; @Entity @Table(name = "TBL_BOOK") public class Book implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "ID") private Integer id; @Column(name = "TITLE") private String title; @Column(name = "AUTHOR") private String author; @Column(name = "ISBN", length = 10, unique = true) private String isbn; @Column(name = "YEAR") private Integer year; @Column(name = "PRICE") private Double price; public Book() { } public Book(String title, String author, String isbn, Integer year, Double price) { this.title = title; this.author = author; this.isbn = isbn; this.year = year; this.price = price; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getIsbn() { return isbn; } public void setIsbn(String isbn) { this.isbn = isbn; } public Integer getYear() { return year; } public void setYear(Integer year) { this.year = year; } public Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } @Override public String toString() { return "Book{" + "id=" + id + ", title='" + title + '\'' + ", author='" + author + '\'' + ", isbn='" + isbn + '\'' + ", year=" + year + ", price=" + price + '}'; } }
Create Hibernate Configuration File
Create the hibernate.cfg.xml hibernate configuration file on the classpath in the src/main/resources folder. In this file, you configure your database properties.
We can include the POJO using the mapping element and provide the class.
<?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 properties --> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/bookstore?serverTimezone=Europe/Brussels</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password"></property> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <!-- show mysql queries output in console --> <property name="hibernate.show_sql">true</property> <!-- manage automatic database creation --> <property name="hibernate.hbm2ddl.auto">create-drop</property> <!-- add resources here --> <mapping class="com.memorynotfound.hibernate.Book"/> </session-factory> </hibernate-configuration>
We can optionally configuere hibernate to automatically create the database tables for us. You can do this by adding the hibernate.hbm2ddl.auto property and assign one of the following values: create, create-drop, update or validate.
Manage Sessions with Hibernate Utility
This class configures/initializes hibernate and facilitates the creation of a hibernate session.
package com.memorynotfound.hibernate; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtil { private static final SessionFactory sessionFactory; static { try { sessionFactory = new Configuration().configure().buildSessionFactory(); } catch (Throwable ex) { throw new ExceptionInInitializerError(ex); } } public static Session getSession() throws HibernateException { return sessionFactory.openSession(); } public static void shutdown() { sessionFactory.close(); } }
Create Application
Now that all ingredients are in place, we can demonstrate this example by inserting a record in the database.
- Obtain the Hibernate Session.
- Start a new Transaction.
- Create and Save the Book POJO.
- Commit the Transaction.
- Close the Hibernate Session.
package com.memorynotfound.hibernate; import org.hibernate.Session; import org.hibernate.Transaction; public class App { public static void main (String...args){ Session session = HibernateUtil.getSession(); Transaction tx = session.beginTransaction(); Book book = new Book(); book.setAuthor("Memorynotfound"); book.setTitle("MySQL / Mariadb + Hibernate Annotation Configuration Example"); book.setIsbnCode("9334537892"); book.setPrice(24.95); book.setYear(2016); session.save(book); tx.commit(); session.close(); HibernateUtil.shutdown(); } }
Console Output
When you run this application, hibernate logs the following information.
Hibernate: drop table if exists TBL_BOOK Hibernate: create table TBL_BOOK (ID integer not null auto_increment, TITLE varchar(255), AUTHOR varchar(255), ISBN varchar(10), YEAR integer, PRICE double precision, primary key (ID)) Hibernate: alter table TBL_BOOK add constraint UK_fxrn17ofk6nxyjgheovkirjvh unique (ISBN) Hibernate: insert into TBL_BOOK (TITLE, AUTHOR, ISBN, YEAR, PRICE) values (?, ?, ?, ?, ?) Hibernate: drop table if exists TBL_BOOK
Download
From:一号门
COMMENTS