title: Hibernate and AspectJ field access
body: <p>I have a question related to intercepting hibernate field accesses. I need to make some checks on fields before they are persisted by Hibernate.</p>
  
  <p>I was thinking about using AspectJ and field access join points, but this does not work with Hibernate. Any other calls/accesses to the fields are well intercepted but not when accessed by hibernate.</p>
  
  <p>So this works ok when using the getters, but this doesn't work if I use field access with hibernate.</p>
  
  <p>I think this is due to the fact that Hibernate is using reflection. </p>
  
  <p>Do you see any way I can intercept this?</p>
  
  <p>I have something like this:</p>
  
  <pre><code>@Entity
  public class Employee {
  
  @Id
  private Long id;
  private String firstName;
  private String lastName;
  
  }
  </code></pre>
  
  <p>and a DAO method doing</p>
  
  <pre><code>@PersistenceContext
  private EntityManager entityManager;
  
  @Transactional
  public Long createEmployee(Employee employee) {
      entityManager.persist(employee);
      return employee.getId();
  }
  </code></pre>
  
  <p>Then I have an aspect like this</p>
  
  <pre><code>@Aspect
  public class MyAspect {
      @Pointcut("get(* test.Employee.*)")
      public void executionGetField() {}  
  
  @Around("executionGetField()")
  public Object onGet(ProceedingJoinPoint thisJoinPoint) {
      System.out.println("executionGetField " + thisJoinPoint.getSignature().getName());
      Object o = null;
      try {
          o = thisJoinPoint.proceed();
          return o;
      } catch (Throwable e) {
          return null;
      }
  }
  </code></pre>
  
  <p>When looking at my traces I can see that any access to the fields are being intercepted by the aspect, except when the object is persisted by Hibernate in the createEmployee method. This is certainly because of the Reflection. So I am wondering how I can make it work with hibernate too.</p>