best practice to synchronize database changes with hibernate mapping file - java

Assuming an existing application which deals with lets say 20+ tables, needs to be rewritten using java/jpa/hibernate and if all the tables already existed, is it the usual/best practice to use hibernate reverse engineering to generate hibernate mapping files?
and if the table structure gets changed, say added/modifed 10 fields in 3 different tables, do the mapping files get edited by hand to reflect the changes in the database?
also if its a brand new application (with new tables), is it the usual/best practice to create the database objects using the ddl generated by hbm2ddl?

Blindly using hbm2dll on production database could lead to data loss.
Take a look at specialized database migration tool like Liquibase or Flyway.
See Hibernate using JPA (annotated Entities) and liquibase.

Related

Designing Hibernate classes with tables

I'm new to hibernate and trying to understand what is the correct way to implement and use it.
Creates tables and then use a tool to generate Hibernate classes
or
Build the classes and create the tables
Our's is a legacy application, so the tables structure is already there..We are just creating the Hibernate classes and using them...
Can someone let me know which is correct and effecient way?
You have automated tools for both sides.
create the classes from a legacy database:
you should use this if you have a runnig database already.netbeans have one of these.
create the tables and relations from entity and embedded clasess:
this way you have to use anotations or a xml file to describe the relations betwen clases and other relational stuff and set table generation strategy to create in the persistence unit the tables will be created automatically usigng the names of the classes for the table and the names of the fields for the columns.
If you already have the database use the tool to generate entity classes
If you use Eclipse then here is a tool to generate POJOs from existing tables:
step by step auto code generation using eclipse plugin
If you are using Intellij check out Intellij Java Persistence API & Hibernate

How to generate hiberate POJO classes from DB tables

I have an sql script that contains DDL's for creating many number of tables, simply will execute this script for creating tables in db.
Now i want to use hibernate to perform CURD operations on that tables, but going through each table for creating POJO's will take time. So, is there any way to generate those POJO with JPA annotations using those DB tables which are already created?
Please help me.
In Eclipse you can use the Telosys Tools plugin
( http://marketplace.eclipse.org/content/telosys-tools )
It works from an existing database and generates different kinds of source files
typically Java beans with JPA annotations
See http://tools.telosys.org
and the tutorials : https://sites.google.com/site/telosystutorial/
http://www.eclipse.org/webtools/dali/ can generate entities from database if you are using eclipse IDE

JPA/Hibernate support for migration?

I'm currently working on a desktop application using JPA/Hibernate to persist data in a H2 database. I'm curious what my options are if I need to make changes to the database schema in the future for some reason. Maybe I'll have to introduce new entities, remove them or just change the types of properties in an entity.
Is there support in JPA/Hibernate to do this?
Would I have to manually script a solution?
I usually let Hibernate generate the DDL during development and then create a manual SQL migration script when deploying to the test server (which I later use for UAT and live servers as well).
The DDL generation in Hibernate does not offer support for data migration at all, if you only do as much as adding a non-null field, DDL generation cannot help you.
I have yet to find any truely useful migration abstraction to help with this.
There are a number of libraries (have a look at this SO question for examples), but when you're doing something like splitting an existing entity into a hierarchy using joined inheritance, you're always back to plain SQL.
Maybe I'll have to introduce new entities, remove them or just change the types of properties in an entity.
I don't have any experience with it but Liquibase provides some Hibernate Integration and can compare your mappings against a database and generate the appropriate change log:
The LiquiBase-Hibernate integration records the database changes required by your current Hibernate mapping to a change log file which you can then inspect and modify as needed before executing.
Still looking for an opportunity to play with it and find some answers to my pending questions:
does it work when using annotations?
does it require an hibernate.cfg.xml file (although this wouldn't be a big impediment)?
Update: Ok, both questions are covered by Nathan Voxland in this response and the answers are:
yes it works when using annotations
yes it requires an hibernate.cfg.xml (for now)
There are two options:
db-to-hibernate - mirror DB changes to your entities manually. This means your DB is "leading"
hibernate-to-db - either use hibernate.hbm2ddl.auto=update, or manually change the DB after changing your entity - here your object model is "leading"

Hibernate project implementation

I am developing a project at Java fresher level.
I had to implement database interaction using Hibernate.
At the first stage, I started using HQL query language. But, later I come to know about Criteria queries through my previous questions.
But, still after learning Criteria, I am not getting what are the steps I should follow to fill and fetch data to and from database.
In fact, what are the packages and classes I need to develop manually and the script or query I need to write to fill/fetch data if I am given a database and table in it, using Criteria ?
Please also tell me, where would be difference when I use different database like PostGresql or MySQL within steps.
In fact, what are the packages and classes I need to develop manually and the script or query I need to write to fill/fetch data if I am given a database and table in it, using Crieteria?
Create an object model and map it to the tables using either annotations or xml mapping files. Classes that can be persisted are called Entities. Using the reverse engineering module of Hibernate Tools, it is possible to generate them.
Create instances of entities, set their attributes and use session.persist(Object) to persist them to the database to "fill data". Use the Criteria API to read from the database and fetch data. Data access is typically done in a data access layer using the DAOs pattern. DAOs expose finders and CRUD methods (Create, Read, Update, Delete).
If all this is new to you, I'd suggest to use Spring, it provides useful support classes and will help you to structure your application following the above pattern. Have a look at the Chapter 12. Object Relational Mapping (ORM) data access.
Please also tell me, where would be difference when I use different database like PostGres or MySQL within steps.
If their physical model differs, you may have to change the mapping of entities. Apart from that, switching from one database to another would require using the appropriate JDBC driver, changing the connection string and the Hibernate dialect (i.e. this is more a matter of configuration).

Hibernate/JPA DB Schema Generation Best Practices

I just wanted to hear the opinion of Hibernate experts about DB schema generation best practices for Hibernate/JPA based projects. Especially:
What strategy to use when the project has just started? Is it recommended to let Hibernate automatically generate the schema in this phase or is it better to create the database tables manually from earliest phases of the project?
Pretending that throughout the project the schema was being generated using Hibernate, is it better to disable automatic schema generation and manually create the database schema just before the system is released into production?
And after the system has been released into production, what is the best practice for maintaining the entity classes and the DB schema (e.g. adding/renaming/updating columns, renaming tables, etc.)?
It's always recommended to generate the schema manually, preferably by a tool supporting database schema revisions, such as the great Liquibase. Generating the schema from the entities is great in theory, but were fragile in practice and causes lots of problems in the long run(trust me on this).
In productions it's always best to have manually generated and review the schema.
You make an update to an entity and create a matching update script(revision) to update your database schema to reflect the entity change. You can create a custom solution(I've written a few) or use something more popular like liquibase(it even supports schema changes rollbacks). If you're using a build tool such as maven or ant - it's recommend to plug the db schema update util into the build process so that fresh builds stay in sync with the schema.
Although disputable, I'd say that the answer to all 3 questions is: let hibernate automatically generate the tables in the schema.
I haven't had any problems with that so far. You might need to clean some field up manually from time to time, but this is no headache compared to separately keeping track of DDL scripts - i.e. managing their revisions and synchronizing them with entity changes (and vice-versa)
For deploying on production - an obvious tip - first make sure everything is generated OK on the test environment and then deploy on production.
Manually, because:
Same database may be used by different applications and not all of
them would be using hibernate or even java. Database schema should
not be dictated by ORM, it should be designed around the data and
business requirements.
The datatypes chosen by hibernate might not be best suited for the application.
As mentioned in an earlier comment, changes to the entities would require manual intervention if data loss is not acceptable.
Things such as additional properties (generic term not java
properties) on join tables work wonderfully in RDBMS but are
somewhat complex and inefficient to use in an ORM. Doing such a
mapping from ORM -> RDBMS might create tables that are not
efficient. In theory, it is possible to build the exact same join
table using hibernate generated code, but it would require some
special care while writing the Entities.
I would use automatic generation for standalone applications or databases that are accessed via the same ORM layer and also if the app needs to be ported to different databases. It would save lot of time in by not requiring one to write and maintain DB vendor specific DDL scripts.
Like Bozhidar said, donĀ“t let Hibernate create&update the database schema.
Let your application create and update the database schema.
For java the best tool to do this is Flyway. You need to create one or more SQL files with DDL statements which are describing your database schema. These SQL files are then executed by Flyway. For more information look at the site of Flyway.
I believe that a lot of what is being discussed or argued here should also be related to if you are more confortable with the code-first or the database-first approach.
Personally, I am more intended to go for latter and, making a reference to Single Responsibility Principle (SRP), I prefer having DB specialist handling the DB and an application specialist handling the application, than having the application handling the DB. Additionally, I am of the opinion that taking too many shortcuts will work fine at the beginning but create unmanageable problems as things grow/evolve.

Categories