Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enable hibernate filter globally with spring-boot & spring-data

I am trying to implement a multi-tenancy by discriminator implementation with Spring Boot and Spring Data.

I have made an abstract class to represent a multi-tenant entity. Something similar to this:

@MappedSuperclass
@FilterDefs({@FilterDef(name = "multi-tenant", parameters = {@ParamDef(name = "tenant", type = "string")})})
@Filter(name = "multi-tenant", condition = "tenant = :tenant")
public abstract class MultiTenantEntity extends GenericEntity {
    @Transient
    private transient String savedTenant;

    @PostLoad
    private void onLoad() throws Exception {
        this.savedTenant = this.tenant;
        onEntityModification();
    }

    @PrePersist
    private void onPersist() {
        if (getId() == null || getId().equals(0l)) {
            tenant = SecurityUtil.getCurrentTenant();
        }
    }

    @PreUpdate
    @PreRemove
    private void onEntityModification() throws Exception {
        String currentTenant = SecurityUtil.getCurrentTenant();

        if (!currentTenant.equals(tenant) || !savedTenant.equals(tenant)) {
            throw new Exception();
        }
    }

    @NotNull
    private String tenant;

    public String getTenant() {
        return tenant;
    }
}

How do I enable the multi-tenant hibernate filter globally?

like image 330
Daniel Gomes Avatar asked May 08 '15 20:05

Daniel Gomes


1 Answers

Using hibernate filters its easy to implement multitenantcies even for Row level ACL as well possible in our application. Instead of discrimators you could use AOP and different filters configurable in your db. Before calling your request method based on the accessing user apply the filter that is enable the hibernate session filter and exeute the request and after successfully request processing disable the filters. thats it. Using this way you could add any number of filters to any number entities that are going to be operated by the current user and you could do the perfect resource (Entity and CRUD) management with this.

like image 113
Hakuna Matata Avatar answered Nov 12 '22 18:11

Hakuna Matata