Tuesday 6 June 2017

Reverse Engineering : Generate Java Persistence Entity from Database

If there is already an existing database , then we could use some reverse engineering tool to automatically generate java persistence entity classes.

You may find below 2 ways from internet :
1. hibernate*-maven-plugin
2. IDE based reverse engine tools

This post would show you how to do it programmatically.





STEP 1 : Create a Maven Project with Below pom.xml




Note :

1. it is org.hibernate:hibernate-tool provides us everything we need to generate java code from database, and it needs org.hibernate:hibernate-core.

2. we use com.h2database:h2 as database for demo purpose , you may use mysql/sql server/oracle or whatever relational database.

3. spring boot is in the pom.xml is because in case you want to see database tables you can use web based H2 console easily.






STEP 2 : Create Service for Generating Java Code from Database




Note :

1. it is org.hibernate.tool.ant.Hbm2JavaExporterTask class generates java code as class name suggested.

2. you may have a look at classes under package org.hibernate.tool.ant to see what other reverse engineering tasks are available


 





STEP 3 : Create Application Launcher and Configuration








Note :

1. we use org.springframework.boot:spring-boot-starter-jdbc to initialize the database

2. based on  above configuration h2 console would be accessible here http://localhost:9001/h2/






STEP 4 : Add Database Scripts to Create Tables for Demo



On startup , Spring Boot would automatically run schema.sql and data.sql as configured with STEP 3 application.properties.







STEP 5 : Run AppLauncher , then System Would Generate Java Source Code as Below












You may refer to project source code here :  https://github.com/junjun-dachi/java-util/tree/master/db-to-java 



JOB DONE.




1 comment:

Flag Counter