开发者

How to set values treated as NULL in JPA relations

I have an Entity "A" with a one-to-many relation (1:n) to another Entity "B". Unfortunately, the (for years existing) database defines the column in B for the primary key of A to NOT NULL, but the relation is not mandatory. Therefore, this column simply gets a -1 if no Emtity A is related.

How can I map this in JPA / Hibernate? I get the following Exception:

Exception in thread "main" 
javax.persistence.EntityNotFo开发者_高级运维undException: 
Unable to find A with id -1

I know this is correct, but maybe there's a workaround?

And please don't blame me for the data model :-)


You could use the @NotFound(action = NotFoundAction.IGNORE) annotation on the B.a property. But this would only work when reading the association. If you want to be able to set B.a to null, and make it insert -1 instead of null in database, I have no idea.


I know turning a data model upside down after years and years isn't a walk in the park. Especially because you'll have to look into every corner of every attached application and so on to see if it's affected. This being a foreign key, chances are that changing it affects alot of things, or at least in a big way.

That said it might still be wellworth talking to the DBA in charge about using some construct to

  • preserve the current data model
  • let you access that data in a different way

Oracle databases (recent versions) have some options like updatable views and pseudo-columns and whatnot. I'm not a DBA myself but I see some potential in the use of a pseudo-column for example that would stand as a copy for the foreign key (towards table/entity A) column except that it would

  • show every -1 value as null
  • makes sure that inserts of a value null are translated into -1 in the column it refers to (possibly by use of a trigger)

If you alter your Hibernate/JPA setup to use that column instead of the original one ..

I just hope you have a DBA with some experience and - even more important - no fear of experimenting (of course on a test environment).

Good luck! Wim

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜