问题
I let hbm2ddl create the tables for me (for dev purposes), and the columns are in reverse order of the fields in the class.
How can I make it create the columns in the same order as the class has?
I think Java classes do not store the order of fields, so Hibernate simply does not know what the order in source is (which seems logical if I think about more complex cases).
But, can I at least ask Hibernate to put PK and FK columns as first ones?
Hibernate 4.0.0 (JBoss AS 7.1.2) MySQL 5.1.x
回答1:
Hibernate team says it's a known limitation and it's impossible to set the order. But you shouldn't rely on hbm2ddl when using Hibernate in production, it's pretty limited thing, for instance it can add column, but it can't remove it. Instead people usually create DB migrations with tools like LiquiBase or FlyWay or DbDeploy, this gives you more flexibility and control over the schema updates.
To describe how this approach helps: let's say you have a UAT environment and you just updated schema - you wanted to add not-null constraint to the existing column. With hbm2ddl it's not possible and you'll force your QAs to re-create the database from scratch. Using the tools described above you'll need to add an SQL file and those tools will run this new script which updates schema respectively. You also may want to set hbm2ddl=verify so that you're sure that current DB schema is up-to-date or vice versa - the Hibernate mapping is correct.
来源:https://stackoverflow.com/questions/12433998/hibernate-reversed-column-order-by-hbm2ddl