Oracle databases seem to consider empty strings and null the same. This contradicts the SQL specification and is therefore a bug.
Unfortunately, it would be almost impossible for Oracle to fix this, because too many applications using Oracle for decades rely on this behavior.
It is therefore crucial to know about this bug when dealing with Oracle databases and to take it into account. As long as the database is accessed explicitly using SQL, SQL*Plus, JDBC, DBI, Pro*C etc., it is easier to deal with. But it is becoming tricky. when using frameworks like Hibernate, where weird errors might be observed. If you have an entity that is persisted, which has a string attribute, it should be legitimately to assign the empty string to it. Once this object travels through Hibernate and gets persisted, this empty string has become null instead, resulting in unexpected NullPointerExceptions. Or if the attribute has the NOT-NULL-constraint in the database, this will result in an Oracle error because of constraint violation. On top of this it might become a semantic issue, when empty strings and null are actually considered to have a different meaning.
An ugly, but practical way to deal with it is to change the getter and setter methods of the string attributes accordingly. Maybe some kind of „magic string“ can be defined, which will never ever occur as a value of this string attribute. The getters and setters use this magic string to internally represent the empty string. It is necessary to annotate the attribute, not the getter, for making this work with JPA or Hibernate.
Example in Java (without JPA annotations, synchronization, toString(), hashCode(), equals() etc. Would be similar for other languages)
public class MyEntity {
private static String MAGIC_VALUE = "_._._«NULL»_._._";
private String value;
public String getValue() {
if (MAGIC_VALUE.equals(value)) {
return "";
} else {
return value;
}
}
public void setValue(String newValue) {
if (MAGIC_VALUE.equals(newValue)) {
throw new IllegalArgumentException("value="+newValue+" not allowed");
} else if ("".equals(newValue)) {
this.value = MAGIC_VALUE;
} else {
this.value = newValue;
}
}
}
To make this work even with short strings, defined as VARCHAR2(1) or VARCHAR2(2) in the database, it is perhaps a good idea to use control characters or UTF-8 characters that are not going to be used otherwise. But it remains an unsatisfactory and ugly solution.
Does anyone have a better idea?
Are there any other databases that have the same issue?
Schreibe einen Kommentar