Dear colleagues,
How can I generate Hibernate hbm xml files & entities classes from existing DB schema?
Sharon
Dear colleagues,
How can I generate Hibernate hbm xml files & entities classes from existing DB schema?
Sharon
You should use the hibernate reverse engineering tools for this. See the hibernate reverse engineering tools documentation for more information.
It's not clear to me how to generate JPA annotated classes, but you might want to think about not using hbm.xml files anymore if this is a new project, favoring annotations.
I've used Hibernate Tools (examples given on their site) with much pleasure. Below, I give details on my specific, advanced and interesting (I think) use case.
Actually, I was facing an interesting challenge on our big project (approaching 800 tables, database driven team)
But mosts tables were not new, I already had the java implementations and the .hbm.xml. Both had sometimes been modified from the DB they were originally generated with, so it was impossible to re-generated them with the guaranty not to break anything. I needed to migrate the Entities, changing as little as possible (that is, only the annotations) !
This needed to be fast also, because our typical old entities have around 100 members (own db columns, plus entity collections coming from reverse foreign keys!).
Note : Two entities couldn't compile with a generated full-constructor, they broke the 256 parameters limit ! But I though this Constructor was useless anyway, who could remember the order of 256 parameters, so I removed it.
For the mapping migration, I used Hibernate Tools (customized as needed, template and code) as follow:
the source of the information was the .hbm.xml files, with the hibernate.cfg.xml file
Note : I had to extract the hibernate.cfg.xml first, replacing the spring bean that used to contain the list. But this was also useful for db tools such as Squirrel, that could use it to enable HQL completion...
the generated output was X2.java files (for X.java class, in the same package) containing only the fields, getters and annotations (no setters or constructors)(generic Sets)
I would use the Eclipse compiler (error "duplicate ...") to double-check my editing, to make it faster and less error-prone (mistake was not an option, we have many client in production !). For each migrated class, I would copy from generated to existing class :
For the curious, this month we're close to 200 annotated entities :-). A typical 100 fields entity requires about 30 minutes work to migrate. Only 300 hours left to finish this cut'n paste for the remaining 600 entities ! ;-)
Netbeans has functionality for generating config files, annotated files and more