Leon
Leon

Reputation: 5

Java / Hibernate call stored procedure after save update or delete

How can i call a stored procedure after an insert, update or delete of the object?

My object looks like this:

@Entity
public class a {
    private String b;
    private String c;

    public a() {
        super();
    }

    // getter setter

    @PostPersist
    @PostUpdate
    @PostRemove
    private void callProcedure() {
        // ???
    }
}

What would be the best possible way to do this?

Upvotes: 0

Views: 565

Answers (1)

Cem Ikta
Cem Ikta

Reputation: 1450

In Java applications you should not call business logic in your entity models. You can set some values in @PrePersist, @PreUpdate in entity for example:

/**
 * Sets createdAt before insert
 */
@PrePersist
public void setCreationDate() {
    this.createdAt = new Date();
}

/**
 * Sets updatedAt before update
 */
@PreUpdate
public void setChangeDate() {
    this.updatedAt = new Date();
}

Or you can get generated primary key values in the @PostPersist method. But stored procedure processing belongs to your service. Your service should call a stored procedure and get results for further processing. You can't use @PostPersist, @PostUpdate and @PostRemove annotations in your service, but you can write afterSave(), afterRemove() methodes in your service to call a stored procedure and process the result of the called stored procedure.

Check this link for examples: How to call stored procedures in JPA

Upvotes: 1

Related Questions