Kannan
Kannan

Reputation: 11

Update date only if record updated with data modification

I'm using Oracle JPA for my project. In my project, we receive file and insert or update (if any field value modified) the records in to database table. There is a chances of receiving duplicate (already received) records without field value modifications.

My need is

  1. If the same record received without any change, date column should not be updated.
  2. If new record or same record with any modification, date column should update.

As an example

First insert:

Record to be inserted:

EmpID  |  Name  | Designation  | Salary
=========================================
00001  |  Raj   | Team Lead    |600000
00002  |  Kumar | Developer    |400000

Table after insert:

Emp ID | Name  | Designation | Salary | DATE
===========================================================
00001  | Raj   | Team Lead   | 600000 | 12-04-2018 01:00:00
00002  | Kumar | Developer   | 400000 | 12-04-2018 01:00:00

Second insert:

Record to be inserted:

EmpID  |  Name  | Designation      | Salary
==============================================
00001  |  Raj   | Team Lead        |600000
00002  |  Kumar | Senior Developer |500000

Table after insert/update:

Emp ID | Name  | Designation      | Salary | DATE
===========================================================
00001  | Raj   | Team Lead        | 600000 | 12-04-2018 01:00:00
00002  | Kumar | Senior Developer | 500000 | 13-04-2018 01:00:00

Here only send row date changed as it is only really modified.

Doing this validation in code is tedious task. Kindly say is there any possible solution.

Upvotes: 0

Views: 1497

Answers (1)

Bejond
Bejond

Reputation: 1198

You need a Listener to set current time

public class BaseEntityListener {

    @PreUpdate
    public void preUpdate(BaseEntity entity) {

        Date date = new Date();
        entity.setUpdateDate(date);
    }

}

Here is Model defination:

@SuppressWarnings("serial")
@MappedSuperclass
@EntityListeners(BaseEntityListener.class)
public class BaseEntity implements java.io.Serializable {

    @Basic(optional = false)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "updateDate")
    private Date updateDate;

And update entity use

        entityManager.merge(model);
        entityManager.flush();

updateDate would be updated when any column is changed. It won't be updated when no column is changed.

Upvotes: 1

Related Questions