未加星标

MySQL / MariaDb + Hibernate Annotation Configuration Example

字体大小 | |
[数据库(mysql) 所属分类 数据库(mysql) | 发布者 店小二04 | 时间 2016 | 作者 红领巾 ] 0人收藏点击收藏

This tutorial shows you how to configure mysql/MariaDB with Hibernate using Annotation Configuration. We demonstrate this by inserting a POJO into the database. This POJO and database are configured using Annotation Configuration.

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 is located 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. This POJO is enhanced with annotations mapping the properties to the database columns.

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.

Previously we created the Book.java POJO. We can include this file using the mapping element.

<?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 annotated 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 References Hibernate API Java Doc Hibernate Official Documentation Download

Download it mysql-mariadb-hibernate-annotation-configuration-example

本文数据库(mysql)相关术语:navicat for mysql mysql workbench mysql数据库 mysql 存储过程 mysql安装图解 mysql教程 mysql 管理工具

主题: HibernateMySQLSQLJavaISBUTAUAUTTIUB
分页:12
转载请注明
本文标题:MySQL / MariaDb + Hibernate Annotation Configuration Example
本站链接:http://www.codesec.net/view/482335.html
分享请点击:


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 数据库(mysql) | 评论(0) | 阅读(50)