Null values
Our current mapping strategy limits our means to specify data
integrity constraints. It is no longer possible to disallow
null
values for properties belonging to derived
classes. We might want to disallow null
values in the
bankName
property. Hibernate will generate a
corresponding database attribute ❶:
Java | package inherit.v2;
...
@Entity @DiscriminatorValue(value = "Bank account")
public class BankAccount extends BillingDetails {
String bankName;
@Column(nullable=false) ❶
public String getBankName() {return bankName;} ... |
Sql | CREATE TABLE BillingDetails (
id bigint(20) NOT NULL AUTO_INCREMENT PRIMARY KEY,
bankName varchar(255) NOT NULL, ❶
... |
Looks good? Unfortunately the attempt to save a bank account ❶ yields a runtime exception ❶:
Java | package inherit.v2; ... public class Persist { ... final CreditCard creditCard = new CreditCard("4412 8334 4512 9416", 1, "05/18/15"); session.save(creditCard); final BankAccount bankAccount = new BankAccount("1107 2 31", "Lehman Brothers", "BARCGB22"); session.save(bankAccount) ❶; ... |
Sql | ...
Feb 19, 2013 10:28:00 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000232: Schema update complete
Hibernate:
insert
into
BillingDetails
(created, number, cardType, expiration, dataType)
values
(?, ?, ?, ?, 'Credit card')
Feb 19, 2013 10:28:00 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 1364, SQLState: HY000
Feb 19, 2013 10:28:00 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Field 'bankName' doesn't have a default value
Exception in thread "main" org.hibernate.exception.GenericJDBCException:
Field 'bankName' doesn't have a default value ❶
...
at inherit.v2.Persist.main(Persist.java:28)
Caused by: java.sql.SQLException: Field 'bankName' doesn't have a default value |
Conclusion: A table per class hierarchy mapping does not allow to specify not null constraints for properties of derived classes.
No. 21
Mapping figures
Q: |
Map the following model to a database: Figure 952. Figure subclasses
Todo: Ref/Fig/figureInherit.fig The two properties The abstract method |
A: |
The main difference to the current
|