@PrePersist with entity inheritance

Posted by gerry on Stack Overflow See other posts from Stack Overflow or by gerry
Published on 2010-03-31T11:59:44Z Indexed on 2010/03/31 12:03 UTC
Read the original article Hit count: 299

Filed under:
|

I'm having some problems with inheritance and the @PrePersist annotation. My source code looks like the following:

_the 'base' class with the annotated updateDates() method:

@javax.persistence.Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Base implements Serializable{

    ...

    @Id
    @GeneratedValue
    protected Long id;
    ...
    @Column(nullable=false)
    @Temporal(TemporalType.TIMESTAMP)
    private Date creationDate;
    @Column(nullable=false)
    @Temporal(TemporalType.TIMESTAMP)
    private Date lastModificationDate;
    ...
    public Date getCreationDate() {
        return creationDate;
    }
    public void setCreationDate(Date creationDate) {
        this.creationDate = creationDate;
    }
    public Date getLastModificationDate() {
        return lastModificationDate;
    }
    public void setLastModificationDate(Date lastModificationDate) {
        this.lastModificationDate = lastModificationDate;
    }
    ...
    @PrePersist
    protected void updateDates() {
      if (creationDate == null) {
        creationDate = new Date();
      }
      lastModificationDate = new Date();
    }
}

_ now the 'Child' class that should inherit all methods "and annotations" from the base class:

@javax.persistence.Entity
@NamedQueries({
    @NamedQuery(name=Sensor.QUERY_FIND_ALL, query="SELECT s FROM Sensor s")
})
public class Sensor extends Entity {
    ...
    // additional attributes
    @Column(nullable=false)
    protected String value;
    ...
    // additional getters, setters
    ...
}

If I store/persist instances of the Base class to the database, everything works fine. The dates are getting updated. But now, if I want to persist a child instance, the database throws the following exception:

MySQLIntegrityConstraintViolationException: Column 'CREATIONDATE' cannot be null

So, in my opinion, this is caused because in Child the method "@PrePersist protected void updateDates()" is not called/invoked before persisting the instances to the database.

What is wrong with my code?

© Stack Overflow or respective owner

Related posts about jpa

Related posts about inheritance