user3120173
user3120173

Reputation: 1788

How to force Hibernate to save invalid values? (Not as stupid as it sounds)

This is more complicated than the title makes it seem. Here's the problem:

I have a Spring Web Flow app which is a series of forms, which the user moves through in a specific order. Two forms, let's call them "Form 2" and "Form 3", populate different fields of the same database table, let's call it "Company." The trouble is, the Company table is all non-nullable fields. So when the user fills out the "Form 2" fields, and tries to save, the "Form 3" fields must be populated with something. For example, I have to save a foreign key value in the "Number of Employees" field.

Then, in the "Form 3", I have to read those fields back in and ignore the values that were just written, and present a blank form to the user. I would like to save a "sentinel" value in the FK field and detect it when it is re-read. However I am using Hibernate and I cannot determine the proper syntax to make Hibernate save what is essentially an "invalid" foreign key in this situation.

The table field I need to flag is this:

NUMBER_OF_EMPLOYEES CHAR(1) DEFAULT ' ' NOT NULL

The column is NOT NULL so I can't just put a NULL in it. The Hibernate/JPA relationship I need to put junk data in is this:

@ManyToOne(optional=true)
@JoinColumn(name = "NUMBER_OF_EMPLOYEES", nullable = true)
private NumberOfEmployees numberOfEmployees;

If the valid keys are, say, "A","B" and "C", I would like to put "X" in here. Is this possible, and if so, how?

Upvotes: 1

Views: 193

Answers (2)

Yaniv Hadad
Yaniv Hadad

Reputation: 21

What about "-1", you can't abuse the system. Change your design or use it as you defined. You can also remove the "not null" (sounds better to me than use "-1").

Upvotes: 0

StormeHawke
StormeHawke

Reputation: 6207

Answer: You don't, at least without modifying the underlying table in the database since your DB server is going to enforce the not-null property even if Hibernate doesn't. Your best bet, absent the ability to use the information below, would be to pass an object around on the Session that gradually gets filled up with data.

However, since you mention you're using Spring, perhaps you can implement AbstractWizardFormController. That allows you to populate data as you go, and once the user finishes the last page you can commit all the data to the DB.

See the javadoc here:

http://docs.spring.io/spring/docs/2.5.6/api/org/springframework/web/portlet/mvc/AbstractWizardFormController.html

and a tutorial here:

http://www.mkyong.com/spring-mvc/spring-mvc-handling-multipage-forms-with-abstractwizardformcontroller/

Upvotes: 2

Related Questions