Kayis Rahman
Kayis Rahman

Reputation: 352

How can implement Triggers in Hibernate?

Two Tables Country And State Both have name and id status columns when insert state table update country column status 'YES' On Hibernate

Like SQL Triggers on Hibernate

How can implement Triggers in Hibernate ????

Upvotes: 2

Views: 4164

Answers (2)

Pras
Pras

Reputation: 1098

You can use JPA listeners for that, something like :

@Entity
@EntityListeners(StateListener.class)
public class State {
}

and your StateListener class, with the annotation @PostPersist

public StateListener {
  @PostPersist
  public void process(State state) {
    // set the status here
  }
}

hibernate doc on this : https://docs.jboss.org/hibernate/orm/4.0/hem/en-US/html/listeners.html

Upvotes: 3

Kent
Kent

Reputation: 195109

I think there is one-many relation between Country-State right? You can in Country Entity impl a method like addState(State state){this.status=true; this.states.add(state)}

If you defined the cascading, saving country object will lead to the state object also get saved. And the status flag of country object was set to true.

You can also implement removeState(State state) there you check if the list (states) is empty after the removing, set the status flag to false.

Upvotes: 0

Related Questions