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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With