Ahmad.Masood
Ahmad.Masood

Reputation: 1309

Using Hibernate to trigger events in Spring integration

I'm bit new with spring integration. I need help in designing a scenario. I have a following entity Model.

@Entity
@Table(name = "account")
public class Account { 

@Column(name="lastmodified")
private Date lastModified;

@Column(name="syncDate")
private Date syncDate;

}

What i want to do is i want to trigger an event when there is a record in database for which lastModified != syncDate

Can you guys please guide me in right direction how i can achieve this with Spring-integration (XML solution will be more apriciated). I already have a method in my DAO Layer which returns Account objects with following scenario

Upvotes: 1

Views: 392

Answers (2)

Artem Bilan
Artem Bilan

Reputation: 121262

For this purpose Spring Integration provide comprehensive JPA module, where you can find <int-jpa:inbound-channel-adapter> exactly for the task to poll data base periodically and perform EntityManager's Query to SELECT data by the criteria.

Take a look into Reference Manual for more information.

If that adapter returns something selected, it becomes as that expected event and emitted as a Message<?> into the channel. You can perform any desired logic subscribing to that channel.

You can find an info about that in that reference manual as well.

Also, please, take a look into Spring Integration JPA sample.

Upvotes: 1

Arif Acar
Arif Acar

Reputation: 1571

For your domain model:

@Entity
@Table(name = "account")
public class Account extends AbstractEntity{ 
  ...
  // another attributes
  ...
}

First step you have to avoid code duplication:

@MappedSuperclass
public class AbstractEntity {

    @Column(name="lastmodified")
    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)  
    private Date lastModified;

    @Column(name="syncDate")
    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)  
    private Date syncDate;

    public void setAuditingInfo(AbstractEntity entityFrom) {
        setLastModified(entityFrom.lastModified());
        // add here another attributes, for ex: createdBy, createdOn..
        // if you didn't set before you can try this:
        setLastModified(new Date());
    }

    // your getter and setter    
}

You can use AbstractEntity for your another domains too.

Service Layer

public Account save(Account account) {
    Account accountPersistent = account;
    if (account.getId() != null) {
        accountPersistent = findById(account.getId()); // This is your find method on your same service class
        accountPersistent.setAuditingInfo(account);
        //set your all attributes here
        accountPersistent.setName(account.getName());
        ...
    }
    return accountRepository.save(accountPersistent);
}        

Upvotes: 0

Related Questions