The partitioned multitenancy available with use of @TenantId annotation doesn’t work for findById from version 6.2.x of hibernate core. After disabling the Filter for Session.find (https://hibernate.atlassian.net/browse/HHH-16179 ) in 6.2.x version, the multitenancy using @TenantId annotation stopped working for direct fetching of the objects. I attach the example small spring boot application which shows the issue. It was created based on the https://spring.io/blog/2022/07/31/how-to-integrate-hibernates-multitenant-feature-with-spring-data-jpa-in-a-spring-boot-application examples. I’m attaching the whole app code to the ticket, but I’m also pasting here the most important part.
@Entity
public class Person {
@Id
@GeneratedValue
private Long id;
@TenantId
private String tenant;
private String name;
public Long getId() {
return id;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person{" + "id=" + id + ", name='" + name + '\'' + '}';
}
}
public interface PersonRepository extends JpaRepository<Person, Long> {
}
@Component
public class TenantIdentifierResolver implements CurrentTenantIdentifierResolver, HibernatePropertiesCustomizer {
private String currentTenant = "unknown";
public void setCurrentTenant(String tenant) {
currentTenant = tenant;
}
@Override
public String resolveCurrentTenantIdentifier() {
return currentTenant;
}
@Override
public boolean validateExistingCurrentSessions() {
return false;
}
@Override
public void customize(Map<String, Object> hibernateProperties) {
hibernateProperties.put(AvailableSettings.MULTI_TENANT_IDENTIFIER_RESOLVER, this);
}
}
The test:
@SpringBootTest
class ApplicationTests {
private static final String ADAM = "ADAM";
private static final String EVE = "EVE";
@Autowired
PersonRepository personRepository;
@Autowired
TenantIdentifierResolver tenantIdentifierResolver;
@Test
void givenCurrentTenantIsSet_shouldNotReturnOtherTenants() {
Person personAdam = new Person();
personAdam.setName(ADAM);
tenantIdentifierResolver.setCurrentTenant(ADAM);
Person adamFromDb = personRepository.save(personAdam);
Person personEve = new Person();
personEve.setName(EVE);
tenantIdentifierResolver.setCurrentTenant(EVE);
Person eveFromDb = personRepository.save(personEve);
Assertions.assertEquals(1, personRepository.findAll().size());
Assertions.assertFalse(personRepository.findById(adamFromDb.getId()).isPresent());
}
}
|