2017-08-17 1 views
0

J'ai eu un problème en essayant de déboguer ceci. Mon but est d'essayer de sauvegarder l'audit de l'intercepteur d'hibernation. J'utilise botte de printemps (1.5.3) et veille prolongée 5.0.12Impossible d'insérer un audit de Hibernate Interceptor

Voici les journaux sql Mise en veille prolongée de sql

Mise en veille prolongée: sélectionnez nextval ('user_sequence')

Mise en veille prolongée: insérer dans les utilisateurs (heure de création, supprimé, description, modifiedby, modified_time, nom, email, activé, mot de passe, numéro de téléphone, rôle_id, gid) valeurs (?,?,?,?,?,?,?,?,?,?,?,?)

Mise en veille prolongée: sélectionnez nextval ('audit_sequence')

POST FLUSH DO NE

Comme vous pouvez le voir, il obtient la valeur nextval pour l'objet d'audit, mais n'insère pas les valeurs.

public void postFlush(@SuppressWarnings("rawtypes") Iterator iterator) throws CallbackException { 
    try { 
     AuditRepository auditRepo =(AuditRepository)ApplicationContextProvider.getApplicationContext().getBean("auditRepository"); 
     synchronized(audits) { 
      for (Long id:audits.keySet()) { 
       auditRepo.save(audits.get(id)); 
      } 
     } 



    } catch (Exception e) { 
     logger.error(e.toString(),e.toString()); 
    } finally { 
     synchronized (audits) { 
      audits.clear(); 
     } 
    } 
    System.out.println("POST FLUSH DONE"); 
} 

Répondre

0

J'espère que cela est cela vous aider, comment je le fais pour mon application (Hibernate 5.2.6):

import java.io.Serializable; 
import java.util.Date; 

import org.apache.logging.log4j.LogManager; 
import org.apache.logging.log4j.Logger; 
import org.hibernate.EmptyInterceptor; 
import org.hibernate.HibernateException; 
import org.hibernate.Session; 
import org.hibernate.type.Type; 

import com.demo.domain.AuditLog; 
import com.demo.util.GlobUtil; 

public class CustomInterceptor extends EmptyInterceptor 
{ 
    private static final Logger log = LogManager.getLogger(CustomInterceptor.class); 

    public static final String OPERATION_TYPE_INSERT = "INSERT"; 

    public static final String OPERATION_TYPE_UPDATE = "UPDATE"; 

    public static final String OPERATION_TYPE_DELETE = "DELETE"; 

    public static final String OPERATION_TYPE_SELECT = "SELECT"; 

    // delete 
    public void onDelete(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) 
    { 
     auditTrail(entity, id, null, state, propertyNames, types, OPERATION_TYPE_DELETE); 
    } 

    // update 
    public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, 
      String[] propertyNames, Type[] types) 
    { 
     return auditTrail(entity, id, currentState, previousState, propertyNames, types, OPERATION_TYPE_UPDATE); 
    } 

    // select 
    public boolean onLoad(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) 
    { 
     // return auditTrail(entity, id, null, state, propertyNames, types, OPERATION_TYPE_SELECT); 
     return true; 
    } 

    // insert 
    public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) 
    { 
     return auditTrail(entity, id, state, null, propertyNames, types, OPERATION_TYPE_INSERT); 
    } 

    private boolean auditable(Object entity) 
    { 
     return (entity instanceof Auditable); 
    } 

    private boolean auditTrail(Object entity, Serializable id, Object[] currentState, Object[] previousState, 
      String[] propertyNames, Type[] types, String operationType) 
    { 
     String prev = ""; 
     String curr = ""; 

     Session session = HibernateUtil.getSessionFactory().openSession(); 

     if (!auditable(entity)) 
     { 
      return false; 
     } 

     try 
     { 
      for (int index = 0; index < propertyNames.length; index++) 
      { 
       if (previousState != null) 
       { 
        prev = (previousState[index] == null) ? "" : previousState[index].toString(); 
       } 

       if (currentState != null) 
       { 
        curr = (currentState[index] == null) ? "" : currentState[index].toString(); 
       } 

       AuditLog auditLog = new AuditLog(id.toString(), entity.getClass().toString(), 
         propertyNames[index], prev, curr, operationType, GlobUtil.getUserName(), new Date()); 

       session.beginTransaction(); 
       session.save(auditLog); 
       session.getTransaction().commit(); 
      } 
     } 
     catch (HibernateException e) 
     { 
      session.getTransaction().rollback(); 
      log.error("Unable to process audit log for " + operationType + " operation", e); 
     } 
     finally 
     { 
      session.close(); 
     } 

     return true; 
    } 
} 

Et bien sûr, dans CustomInterceptor déclarer XML ou en java.

<property name="entityInterceptor"> 
    <bean class="com.demo.common.CustomInterceptor"/> 
</property> 
+0

J'utilise botte de printemps. Dans application.properties, spring.jpa.properties.hibernate.ejb.interceptor = AuditInterceptor. J'utilise les données de printemps jpa et sping. Je vais essayer votre approche de l'utilisation de HibernateUtil. mais je voudrais l'obtenir fonctionnant avec le ressort – Paul

+0

@paul je le fais en fait au printemps mais pas la botte de ressort. – shadow

+0

@paul faire un point d'arrêt à cette ligne service.add (audits.get (id)); pour voir s'il y a des valeurs dedans? – shadow

0

Je l'ai résolu moi-même. J'ai changé le code comme suggéré dans EntityManager.persist() doesn't insert data when using @Transactional

@Override 
public void postFlush(@SuppressWarnings("rawtypes") Iterator iterator) throws CallbackException { 
    try { 
     AuditService service = (AuditService)ApplicationContextProvider.getApplicationContext().getBean("audit"); 

     synchronized(audits) { 
      for (Long id:audits.keySet()) { 
       service.add(audits.get(id)); 
      } 
     } 
    } catch (Exception e) { 
     logger.error(e.toString(),e.toString()); 
    } finally { 
     synchronized (audits) { 
      audits.clear(); 
     } 
    } 
} 


@Service("audit") 
public class AuditServiceImpl implements AuditService { 

@PersistenceContext(type = PersistenceContextType.EXTENDED) 
private EntityManager em; 


public Audit add(Audit obj) { 
    em.persist(obj); 

    return obj; 

} 

}