Hi.
I'm using Hibernate as a JPA implementation in a Java SE context
and a MySQL database.
I ran into a problem when I tried to persist entities where some
of their properties have default values at the database level.
To illustrate my problem, here is a simple example.
Let's say we have the following DDL
Code:
CREATE TABLE `Deletions` (
`id` int(11) NOT NULL auto_increment,
`deleted` datetime NOT NULL default '0000-00-00 00:00:00',
PRIMARY KEY (`ID`)
);
and the corresponding entity
Code:
public class Deletions {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private Date deleted;
public Deletions() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Date getDeleted() {
return deleted;
}
public void setDeleted(Date deleted) {
this.deleted = deleted;
}
}
When I try to persist a new entity in a transaction like this
Deletions d = new Deletions();
em.persist(d);
I get
com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException: Column 'deleted' cannot be null
I understand why this happens: When Hibernate tries to persist
the entity the property deleted is null. But the DDL says column
deleted must not be null.
Is their a way to tell Hibernate to not include uninitialized properties
in insert-statements or a way to specify default values for such
properties?
Right now I'm setting some properties to their default values in the
no-arg constructor, but I'm looking for a better solution.
Best regards,
Achim