0

I’m building a multi-tenant Spring Boot application where all tenants share the same database and schema, but data is separated by a hospital_id column in each table.

Here’s my setup:

  • Same database
  • Same schema
  • Tables have a hospital_id column

I want to automatically filter data per tenant (hospitalId) without adding WHERE hospital_id = :hospitalId manually in every query.

@Entity
@FilterDef(name = "hospitalFilter", parameters = @ParamDef(name = "hospitalId", type = "string"))
@Filter(name = "hospitalFilter", condition = "hospital_id = :hospitalId")
public class PatientEntity {
    @Id
    private Long patientId;

    @Column(name = "hospital_id")
    private String hospitalId;

    // other fields
}

I tried using Hibernate filter, but I think this is not working with jpa repo.

2
  • If you're working in a medical environment, I suspect you should use separate databases or schemas. Would that not also simplify this design? Commented Jun 14 at 21:49
  • @halfer Yes, separating databases or schemas is a good idea. But in my case, all hospitals use the same schema, so having different databases or schemas can be costly and harder to manage. Commented Jul 5 at 16:38

1 Answer 1

2

You can use Hibernate Filter with Spring Boot JPA but you have to enable it. I think you are missing the code to enable it.

Refer to Using Hibernate Filter with Spring Boot JPA and How can I activate hibernate filter in Spring Boot. (This one contains Git repo as an example too).

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, Yasin! It worked perfectly. However, I have one more question: it's working fine for the findAll() method, but when I call findById(), the filter isn’t being applied
As per Hibernate docs, "Filters apply to entity queries, but not to direct fetching." - docs.jboss.org/hibernate/orm/5.6/userguide/html_single/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.