1

I use Spring Data CrudRepository and I want to use Hibernate Filters feature (in my case for soft deletion) with it. To activate filter I need access to Hibernate session (it seems there is no way to enable filters by default in Hibernate - HHH-3815). The problem is that I don't have access to Hibernate session since Spring CrudRepository is just an interface.

I was wondering if there is some standard way to make these technologies work together?

Or the only option is aspect (pointcuts something like * org.hibernate.SessionFactory.openSession(..) or @annotation(org.springframework.transaction.annotation.Transactional)?

volkovs
  • 1,153
  • 2
  • 11
  • 24
  • JPA offers `EntityListener`s, which can offer similar functionality to Hibernate filters. If you really want to work directly with the Hibernate `Session`, you can inject the `EntityManager` as `@PersistenceContext EntityManager entityManager;` and then call `entityManager.unwrap(Session.class)` on it. This will require JPA 2.0. If you are using JPA 1.0, you can call `(Session) entityManager.getDelegate()`. – manish Aug 16 '15 at 04:12
  • It's better to use the History Table pattern for soft delete. For table `foo`, create a table `foo_history` and copy rows to the latter on delete – Neil McGuigan Aug 17 '15 at 19:45
  • @NeilMcGuigan thanks for reply. There are still references to deleted entities and I still want fetch them if referenced directly, but hide in all "multiple values queries" as well as in all joined records. Hibernate filters are just perfect for that and they work smoothly in regular repositories almost without changes to my domain or ORM. I am not sure I can reach the same level of transparency with History Tables (+ overhead on supporting double schema). – volkovs Aug 20 '15 at 11:07
  • @manish thanks for reply. Could you please provide some details how EntityListener can provide similar functionality. There is `@PostLoad` callback, but there is no `@PreLoad`, so I could activate the filter (read as modify SQL coming) before querying the entities. Did you mean Hibernate Listeners (not filters)? – volkovs Aug 20 '15 at 11:15
  • JPA entity listeners work with managed entities. `@PreLoad` as a listener event does not make sense because an entity is not "managed" before it has been loaded (for all the ORM knows, the database operation may not return any rows at all or may be a malformed query altogether). As I mentioned earlier, you can always use the underlying Hibernate `Session` directly if you want to or use a `hibernate.cfg.xml` file as well. – manish Aug 20 '15 at 12:41
  • 1
    No standard way and even no dream to hook with custom code into hardcoded Spring Data initialization. The only solution I've found so far working is here https://stackoverflow.com/a/32230857/320761 – Lukasz Frankowski Jun 16 '18 at 14:20

0 Answers0