Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Hibernate to ignore table columns not in entity?

I'm using Java with Spring MVC and Hibernate. I have a bunch of entities and everything works fine. If, however, I add a column to one of my database columns, my service will start crashing until I also update the relevant java entity class with the new column.

Is there a way to tell Hibernate to ignore database columns it doesn't recognize? If you want to have a field in your entity that's not in your DB table, you would use @Transient on the field. I want the inverse of that.

If this is not possible, how do Hibernate services get deployed when there's a database update that has to go along with it?

like image 387
AlexG Avatar asked Mar 15 '23 20:03

AlexG


1 Answers

Hibernate will not "crash" after new columns were added to a table managed by Hibernate. Hibernate scheme validation goes only as far as verifying that the mapped columns can be stored in the database, but will not look for unmapped columns in the database.

What is likely causing your problem is a new NOT-null field. Adding such a field will make it impossible for Hibernate to persist anything into that table since it is oblivious to the existence of this field and will not provide it at insertion-time. Solutions to this problem are:

  • Providing DEFAULT in the alter table operation for clients that do not use this field
  • Not marking the field not-null and performing nullability checks in another layer
  • Using pre-insert triggers to populate the empty fields
  • Alternatively you can even add the new field first, deploy your new version of your application, then mark the new field as not-null.
like image 95
Gergely Bacso Avatar answered Apr 27 '23 11:04

Gergely Bacso