The partitioned multitenancy available with use of @TenantId annotation doesn’t work for *direct fetching* (*findById)* in version 6.2.x of hibernate core.
After disabling the Filter for Session.find ([https://hibernate.atlassian.net/browse/HHH-16179|https://hibernate.atlassian.net/browse/HHH-16179|smart-link] ) in 6.2.x version, the multitenancy using @TenantId annotation stopped working for direct fetching of the objects.
I attach ’m attaching the example of 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|https://spring.io/blog/2022/07/31/how-to-integrate-hibernates-multitenant-feature-with-spring-data-jpa-in-a-spring-boot-application|smart-link] examples. I’m attaching the whole app code to the ticket, but I’m also pasting here the most important part:
{code:java}@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 + '\'' + '}'; } }{code}
{code:java}public interface PersonRepository extends JpaRepository<Person, Long> { }{code}
{code:java}@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); } }{code}
The test:
{code:java}@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()); //THIS CONDITION FAILS WHEN USING HIBERNATE VERSION 6.2 Assertions.assertFalse(personRepository.findById(adamFromDb.getId()).isPresent()); }
}{code} |
|