Friday, June 10, 2011

Reverse Engineer Hibernate Entities from a DB

I may make a use of this on a current object, so I had to google around and this is what I camep up with.

1. Install hibenate-tools for eclipse
    Eclipse -> Help -> Install New Software -> Add
    Location: hibernate-tools


OK -> Expand Data Services and select Hibernate Tools


-> Next -> Restart at the prompt.

Create new Java Project with three source folders


Import the mysql-driver jar to the lib folder and add it to the classpath (in my case mysql-connector-java-5.1.13-bin.jar)

Select the config folder -> File ->New -> Other -> Hibernate Configuration File -> Next -> Next
Fill out the Dialect, the Driver class, the Connection URL, the username and password,
Check Create a console Configuration -> Next

Select the Annotations radio-button

Select the options tag, Select MySQL from the Database Dialect drop-down -> Finish

File -> New -> Other -> Hibernate -> Hibernate Reverse Engineering File -> Next -> Next

Select the console configuration you created in the previous step from the
'Console Configuration' drop-down (in my case hibernate reverse) -> Hit the Refresh button bottom left -> Select the Database Schema from the left -> Hit Include

Finish. You should see two new files in your config folder:

Finally, you want to switch to Hibernate perspective:
Window -> Open Perspective -> Other ->Hibernate

Run ->Hibernate Code Generation -> Hibernate Code Generation Configurations ->
Double click Hibernate Code Generation ->
Select the Console Configuration from the drop-down ->
Select the Output directory as the src dir on the project ->
Select Reverse Engineer from JDBC Connection

Select the Exporters Tab -> Select Both Use Java 5 Syntax and EJB 3 annotations ->
Put a check in Domain Code(.java) -> Apply -> Run

And...BOOM...Now under the src folder you should see a 'default package' with all of your entities: