Dave
Dave

Reputation: 19320

JPA: How do I prevent a field from being written back into the database?

I’m using Hibernate 4.3.6.Final, JPA 2.1, MySQL 5.5.37, and Spring 3.2.11.RELEASE. I have an entity with the following field and getter (no setter) …

@Column(name="CREATED_ON")
private java.util.Date createdOn = new java.util.Date();

public java.util.Date getCreatedOn()
{
    return createdOn;
}   // getCreaetdOn

I notice when I execute JPA save transactions, for instance …

public T save(T obj)
{
    if (obj != null)
    {
        final T id = (T) getId(obj);
        if (id == null)
        {
            m_entityManager.persist(obj);
        }
        else
        {
            obj = m_entityManager.merge(obj);
        }   // if
    }   // if
    return obj;
} 

Hibernate/JPA will attempt to write a “NULL” into the “CREATED_ON” field in the INSERT statement. How do I configure things within JPA so that if no value is present it doesn’t attempt to write back a value at all? The reason I ask is because by default the value is set to the MySQL “CURRENT_TIMESTAMP” value and this value isn’t used if an explicit “NULL” is inserted.

Thanks, - Dave

Upvotes: 0

Views: 239

Answers (1)

Predrag Maric
Predrag Maric

Reputation: 24433

Try this for the field mapping

@Column(name="CREATED_ON", insertable = false, updateable = false)

Upvotes: 1

Related Questions