I am using Hibernate Tools to generate my entity.
Now I have to edit and add new annotations as (@ JsonIgnore
etc ...)
My problem is this:
In the future I will have to add extra columns in my database, and regenerate my entity with hibernate tools.
Now my entity are overwritten losing my edits.
exist a pattern? or a solution?
not to lose my changes
thank you.

- 2,395
- 2
- 21
- 27
-
Why not generate database schema from your entities? – Neil McGuigan Aug 14 '15 at 19:36
2 Answers
Solution 1
I will recomend to not regenerate your entities. I recommend to manually update your entity with the new columns and use this settings:
<property name="hibernate.hbm2ddl.auto">validate</property>
To be sure that you column mapping is working.
Solution 2
I never try this, but other solution is extends the entity class. Example:
@Entity
public class YourGeneratedEntity {
}
public class YourClassWithModifications extends YourGeneratedEntity {
}
With this approach, your modifications that use the attributes from the entity will not be loosed when you regenerate the entity class.
I'll be very political here, I think the comment from @Neil McGuigan is really bad advice. and the 2nd point in the answer from Dherik is as bad.
The tool to autogenerate is provided to simplify the use of hibernate/JPA from an existing database. Once you create the initial entities, you never, ever re-create them again the reason is quite simple, the tool is stupid and the only thing it can do is assume that you want to map your objects in the exact same way as they are in the DB... it won't create any UserTypes, Embeddables, SecondaryTable or Converters annotations for you. It won't know (or do a bad job) into mapping associations, as in general you should prefer unidirectional associations.
Once you have the initial mapping you need to work on it to convert it into a proper Object Oriented model.
The bottom line is: if your Entity objects have the same structure and shape as your database, you're doing something wrong. Object Oriented design and Relational Modelling are two very different things. There's even a term called Object-Relational impedance mismatch to explain this difference.

- 28,839
- 5
- 58
- 88
-
I agree with you, I'm only trying to resolve his problem with my second solution :) – Dherik Aug 14 '15 at 20:34
-
1You can automatically create table inheritence from jpa to sql, but not the other way around, so no, it's not terrible advice. – Neil McGuigan Aug 15 '15 at 23:52
-
1Niel, it's bad advice as it becomes more difficult to maintain, and the structure that you can generate from JPA is just a shadow of what you can do with custom build DDL scripts that fully uses the features of the database engine. A good example is partitioning. Most database engines support table partitioning, but there's no way of specifying that from JPA. Generating the schema from the JPA annotation only works for trivial, non-production scenarios. – Augusto Aug 16 '15 at 12:05