I am using Hibernate 6.1.7.Final. (with spring-boot-starter-data-jpa:3.0.4, com.h2database:h2:2.1.214)
I registered a PreLoadEventListener in the registry and applied it to receive PreLoadEvent as a listener.
@Component
public class EncryptionListener implements PreInsertEventListener, PreUpdateEventListener, PreLoadEventListener {
...
@Override
public void onPreLoad(PreLoadEvent event) {
Object[] state = event.getState(); // is always null T.T
String[] propertyNames = event.getPersister().getPropertyNames();
Object entity = event.getEntity();
// todo: fieldDecrypter.decrypt(state, propertyNames, entity);
}
}
In 6.x, when debugging, getState() always returns null.
In 5.x, it was returning the value read directly from the DB (i.e. the encrypted value before decryption).
I also attach the configuration and entity code
@RequiredArgsConstructor
@Service
public class HibernateListener {
private final EntityManagerFactory entityManagerFactory;
private final EncryptionListener encryptionListener;
@PostConstruct
private void init() {
SessionFactoryImpl sessionFactory = entityManagerFactory.unwrap(SessionFactoryImpl.class);
EventListenerRegistry registry = sessionFactory.getServiceRegistry().getService(EventListenerRegistry.class);
registry.getEventListenerGroup(EventType.PRE_LOAD).appendListener(encryptionListener);
registry.getEventListenerGroup(EventType.PRE_UPDATE).appendListener(encryptionListener);
registry.getEventListenerGroup(EventType.PRE_INSERT).appendListener(encryptionListener);
}
}
@Entity
@ToString
public class Phone {
@Id
private UUID id;
private String phoneNumber;
private String address;
// getter, setter, no-argument constructor
}
Translated with DeepL Translate: The world's most accurate translator (free version)