Обсуждение: Foreign keys with values of zero rather than null

Поиск
Список
Период
Сортировка

Foreign keys with values of zero rather than null

От
"Campbell, Lance"
Дата:

I map data from rows in tables to objects in Java. When I map integers in the database I map them to integer primitives in Java.  The challenge I am running into is what do I do when a table has a integer foreign key that is null.  Ideally when a table in PostgreSql has a foreign key that does not exist I would like the value to be zero rather than null.  This works really well for me because I NEVER use a key with the value of 0.

 

Is there some way for me to tell PostgreSql that a zero is the same as null when using foreign keys that map to integers?  That way I can still use cascade delete.  The only way for me to get around this issue is to remove the foreign key constraint for cascade delete.

 

Any help would be appreciated.

 

Thanks,

 

Lance Campbell

Software Architect/DBA/Project Manager

Web Services at Public Affairs

217-333-0382

 

Re: Foreign keys with values of zero rather than null

От
"Kevin Grittner"
Дата:
"Campbell, Lance" <lance@illinois.edu> wrote:
> I map data from rows in tables to objects in Java. When I map
> integers in the database I map them to integer primitives in Java.
> The challenge I am running into is what do I do when a table has a
> integer foreign key that is null.  Ideally when a table in
> PostgreSql has a foreign key that does not exist I would like the
> value to be zero rather than null. This works really well for me
> because I NEVER use a key with the value of 0.

I would definitely use NULL in the database to indicate that a value
is unknown or not applicable.  Really.  Always.

How you map that to your Java objects is another issue -- if you
used an Integer object, you would have a natural mapping of NULL in
the database to a Java null and back again.  That's what I normally
do.  In my view, you need a really good reason to map to the
primitive, especially since Java has added the automatic boxing and
unboxing features.

If you feel compelled to micro-optimize to primitives, you need to
have some way to map the NULLs to your magic number and back again.
The former is pretty easy if you use zero as your magic number,
since getInt returns zero for a NULL, leaving it to you to check
wasNull to determine whether it's really a NULL or a zero, that
direction is easy.

http://java.sun.com/javase/6/docs/api/java/sql/ResultSet.html#getInt(int)

http://java.sun.com/javase/6/docs/api/java/sql/ResultSet.html#wasNull()

Going the other direction, you need some way to convert a zero in
that column to a NULL in the database.  Exactly how you do that
depends on how you are doing your mapping -- unless you want to try
to use PostgreSQL rules to rewrite your statements or some such.

-Kevin