Thursday, 2 July 2020

How to get Database Change Notification ?

I am not writing the whole blog here .
Found a good document on oracle .Please refer below .

https://docs.oracle.com/cd/E11882_01/java.112/e16548/dbchgnf.htm#JJDBC28820


Note: As per my analysis this feature is not working/deprecated in 12.1 c oracle version and again it is available in 12.2 c oracle .

Its a good feature to get notified automatically if there is any changes in Table .

How to get notification if Table/Entity perform any operation ?

The below example will show ,if there is any operation in a entity then how we will get notification in JPA+Hibernate .

Note: If the operation is in only application not in backend operation (like update,delete,add query in oracle developer directly)

While defining Entity class need to add below annotation .

 @EntityListeners(MyEntityListener.class)

We will discuss about  MyEntityListener.class also.
Example  of Entity class :

@Entity
@EntityListeners(MyEntityListener.class)
public class MyEntity {
  @Id
  @GeneratedValue
  private int id;
  private String msg;

  public MyEntity() { }

  public MyEntity(String msg) {
      this.msg = msg;
  }
    .............
}


Listner class:
In this class we will get notification if there is any operation in entity .

Example:
public class MyEntityListener {

  @PrePersist
  void onPrePersist(MyEntity myEntity) {
      System.out.println("MyEntityListener.onPrePersist(): " + myEntity);
  }

  @PostPersist
  void onPostPersist(MyEntity myEntity) {
      System.out.println("MyEntityListener.onPostPersist(): " + myEntity);
  }

  @PostLoad
  void onPostLoad(MyEntity myEntity) {
      System.out.println("MyEntityListener.onPostLoad(): " + myEntity);
  }

  @PreUpdate
  void onPreUpdate(MyEntity myEntity) {
      System.out.println("MyEntityListener.onPreUpdate(): " + myEntity);
  }

  @PostUpdate
  void onPostUpdate(MyEntity myEntity) {
      System.out.println("MyEntityListener.onPostUpdate(): " + myEntity);
  }

  @PreRemove
  void onPreRemove(MyEntity myEntity) {
      System.out.println("MyEntityListener.onPreRemove(): " + myEntity);
  }

  @PostRemove
  void onPostRemove(MyEntity myEntity) {
      System.out.println("MyEntityListener.onPostRemove(): " + myEntity);
  }
}


The above annotation will take responsible for the notification .

If any operation will be there in the mentioned table in  your application then we will get notification
.
Note:We can use other annotation in Entity class as well.