Generating Database Objects from Hibernate Entities
In the usual scenario, developers will tend to create database objects first before the entities. This is called bottom to top approach. You start with creating your bottom (database) and create all the way up to the top (java). It’s beneficial of course, since you usually plan the data flow before you even create the services so that you can pattern them to how you designed your database.
Although this is the norm, it’s also a good approach to start on top (java) up to the bottom (database). This is called “you guess it”, top to bottom approach. You can create your java source code entities first and create the scheme based on them. This will allow you to create the services first without the dependency of having to connect to a database or you can always use H2 database, an in memory database that flushes after destroying your application context.
In this post, I’ll be giving a tutorial on how to create database objects form hibernate entities. This project is an svn comparison tool api. I designed it in such as a way that this api project will directly interact with the database.
Pre-requisites:
- Eclipse
- Mysql Database
1. Create an application and include the libraries needed
It doesn’t really matter if it’s a web app, applet or a desktop application, but I highly recommend creating the skeleton using maven artefacts – just so you have the benefits of automatic dependency management.
2. Create the entity
Let’s create an entity.
UcRequest.java
package com.macq.ci.tools.entities; import java.io.Serializable; import java.sql.Date; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.PrePersist; import javax.persistence.PreUpdate; import javax.persistence.Table; import org.hibernate.annotations.Generated; @Entity @Table(name="uc_request") public class UcRequest extends UcOwner implements Serializable { @Id @Column(name = "id") @GeneratedValue(strategy=GenerationType.IDENTITY) private Long id; @Column(name="email",length=100) private String email; @Column(name="status",length=25) private String status; @Column(name="svn_url_1",length=500) private String svnUrl1; @Column(name="svn_url_2",length=500) private String svnUrl2; @Column(name="svn_url_1_name",length=500) private String svnUrl1Name; @Column(name="svn_url_2_name",length=500) private String svnUrl2Name; public String getSvnUrl1Name() { return svnUrl1Name; } public void setSvnUrl1Name(String svnUrl1Name) { this.svnUrl1Name = svnUrl1Name; } public String getSvnUrl2Name() { return svnUrl2Name; } public void setSvnUrl2Name(String svnUrl2Name) { this.svnUrl2Name = svnUrl2Name; } public String getSvnUrl1() { return svnUrl1; } public void setSvnUrl1(String svnUrl1) { this.svnUrl1 = svnUrl1; } public String getSvnUrl2() { return svnUrl2; } public void setSvnUrl2(String svnUrl2) { this.svnUrl2 = svnUrl2; } @OneToMany(fetch = FetchType.EAGER,mappedBy="id",cascade=CascadeType.ALL) private List ucRequestOutput; public UcRequest() { // TODO Auto-generated constructor stub } public UcRequest(Long id, String email, String status) { this.id = id; this.email = email; this.status = status; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public List getUcRequestOutput() { return ucRequestOutput; } public void setUcRequestOutput(List ucRequestOutput) { this.ucRequestOutput = ucRequestOutput; } }
3. Configure the hibernate entities and properties
Next, we configure the hibernate entities and properties. Put the following files on the resources folder.
hibernateContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/context classpath:spring-context-4.1.xsd"> <context:property-placeholder location="classpath:hibernate/persistence-sybase.properties-${env.p}.properties" /> <bean id="dataSource" destroy-method="close" class="org.apache.tomcat.dbcp.dbcp.BasicDataSource"> <property name="driverClassName" value="${jdbc.driverClassName}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.user}" /> <property name="password" value="${jdbc.pass}" /> </bean> <bean id="hibernateProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> <property name="properties"> <props> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.generate_statistics">true</prop> <prop key="hibernate.hbm2ddl.auto">create-drop</prop> <prop key="hibernate.jdbc.batch_size">50</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.id.new_generator_mappings">true</prop> <prop key="hibernate.cache.use_query_cache">false</prop> <prop key="hibernate.cache.use_second_level_cache">false</prop> <prop key="org.hibernate.envers.audit_table_suffix">_AUDIT</prop> <prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop> </props> </property> </bean> <bean id="hibernateAnnotatedClasses" class="org.springframework.beans.factory.config.ListFactoryBean"> <property name="sourceList"> <list> <value>com.macq.ci.tools.entities.UcRequest</value> </list> </property> </bean> <bean id="persistenceExceptionTranslationPostProcessor" class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" /> <bean id="hibernateSessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="hibernateProperties" ref="hibernateProperties"></property> <property name="annotatedClasses" ref="hibernateAnnotatedClasses" /> <property name="entityInterceptor"> <bean class="com.macq.ci.tools.interceptors.UcOwnerInterceptor" /> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="hibernateSessionFactory" /> </bean> </beans>
and the properties file!
hibernate.properties
# jdbc.X jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url= jdbc.user=root jdbc.pass=password # hibernate.X hibernate.dialect=org.hibernate.dialect.MySQLDialect hibernate.show_sql=true hibernate.hbm2ddl.auto=create-drop #hibernate.hbm2ddl.auto=validate
The tiny bit here that we need to add is the hmb2ddl property. We need to set it to create-drop which means that it drops and creates new entities upon initializing the context of the application
4. Database changes
You can now see that the database object UcRequest was created. This is created once the application is initialize.
Download the Eclipse project of this tutorial:
This was an example of generating database objects using entities in Java.
You can download the full source code of this example here: generate-database-objects-from-entities