孤灯野火
畅想的天空
posts - 2,comments - 4,trackbacks - 0
1.在JPA的配置文件中properties中引入监听器
             <property name="hibernate.ejb.event.post-insert" value="com.core.util.PostSaveEventListener" />
                       <property name="hibernate.ejb.event.post-update" value="com.core.util.PostUpdateEventListiner" />
            <property name="hibernate.ejb.event.post-delete" value="com.core.util.PostDeleteEventListener" />

当JPA操作完成后,自动调用PostSaveEventListener,PostUpdateEventListiner,PostDeleteEventListener方法,支持联合主键取主键值,不支持外键更新,不支持属性为集合的变化记录,如需要外键更新可根据需要扩展,以下为save、update、delete三个操作类
package com.core.util;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.hibernate.event.spi.PostInsertEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.unilogi.core.bean.LoginUserInfo;

/**
 * 
 * <p>
 * PostSaveEventListener.
 * </p>
 * 
 * 
@author liu_dawei
 
*/

@SuppressWarnings(
"rawtypes""unchecked""serial" })
public class PostSaveEventListener extends org.hibernate.ejb.event.EJB3PostInsertEventListener {

    
private static final Logger logger = LoggerFactory.getLogger(PostSaveEventListener.class);

    
private static PostSaveEventListener instance = null;

    
public static PostSaveEventListener getInstance() {

        
if (null == instance) {

            instance 
= new PostSaveEventListener();
        }

        
return instance;
    }


    
private enum OperationType {
        CREATE, UPDATE, DELETE
    }


    @Override
    
public void onPostInsert(PostInsertEvent event) {

        
try {
            Connection con 
= event.getSession().connection();

            Map map 
= getContent(event);

            postOperation(con, map, OperationType.CREATE.ordinal());
        }
 catch (Exception e) {
            logger.error(e.getMessage());
        }


    }


    
/**
     * con: dataBase Connection map: result map
     * <p>
     * </p>
     * 
     * 
@param con
     * 
@param map
     * 
@param operation
     * 
@throws Exception
     
*/

    
public void postOperation(Connection con, Map map, int operation) throws Exception {

        
try {
            String tableName 
= map.get("tableName"== null ? "" : map.get("tableName").toString();
            StringBuffer PKNameBuffer 
= new StringBuffer();
            
if (null != map.get("pkName")) {
                List pkList 
= (List) map.get("pkName");
                
for (int i = 0; i < pkList.size(); i++{
                    
if (false == PKNameBuffer.toString().equals("")) {
                        PKNameBuffer.append(
",");
                    }

                    Map tempMap 
= (Map) pkList.get(i);
                    Set tempsets 
= tempMap.keySet();
                    Iterator it 
= tempsets.iterator();
                    
while (it.hasNext()) {
                        Object obj 
= it.next();
                        PKNameBuffer.append(obj.toString()).append(
"=").append(tempMap.get(obj));
                    }


                }

            }


            String pkName 
= PKNameBuffer.toString();

            con.setAutoCommit(
false);

            String sql 
= "insert into M_Data_Log(PK_Value, Description, Old_Value, New_Value, Operation_Type, Table_Name, User_Id,Update_Time, Data_Log_Id) "
                    
+ "values(?,?,?,?,?,?,?,CURRENT_TIMESTAMP, M_Data_LOG_SEQ.nextval)";

            PreparedStatement ps 
= con.prepareStatement(sql);
            ps.setString(
1, pkName);
            
if (operation == OperationType.CREATE.ordinal()) {
                ps.setString(
2"save " + tableName);
            }

            
if (operation == OperationType.UPDATE.ordinal()) {
                ps.setString(
2"update " + tableName);
            }

            
if (operation == OperationType.DELETE.ordinal()) {
                ps.setString(
2"delete " + tableName);
            }


            ps.setString(
3, map.get("previousproperty"== null ? "" : map.get("previousproperty").toString());
            ps.setString(
4, map.get("afterproperty"== null ? "" : map.get("afterproperty").toString());
            ps.setLong(
5, operation);
            ps.setString(
6, tableName);

            LoginUserInfo loginUserInfo 
= SessionInfoManager.getContextInstance(
                    MessageManager.getInstance().getHttpServletRequest()).getCurrentUser();

            ps.setInt(
                    
7,
                    loginUserInfo 
== null ? Integer.parseInt("0") : Integer.parseInt(String.valueOf(loginUserInfo
                            .getUserId())));

            ps.execute();
            con.commit();
            ps.close();
        }
 catch (Exception e) {

            
if (null != con) {
                
try {
                    con.rollback();
                }
 catch (SQLException e1) {
                    
// TODO Auto-generated catch block
                    e1.printStackTrace();
                }

            }


            
throw new Exception(e.getMessage());
        }
 finally {
            
try {
                
if (null != con && con.isClosed() == false{
                    con.close();
                }

            }
 catch (SQLException e) {
                e.printStackTrace();
            }

        }


    }


    
public Map getContent(PostInsertEvent event) throws IllegalArgumentException, IllegalAccessException,
            InstantiationException, ClassNotFoundException 
{

        Map map 
= new HashMap();

        
// get table
        Serializable[] serializables = event.getPersister().getPropertySpaces();
        map.put(
"tableName", serializables[0]);

        
// get PK
        String identifierPropertyName = event.getPersister().getIdentifierPropertyName();

        Field[] tempFields 
= event.getEntity().getClass().getDeclaredFields();
        
for (int i = 0; i < tempFields.length; i++{
            
if (tempFields[i].getName().equals(identifierPropertyName)) {
                List tempList 
= new ArrayList();
                
// if PK is Primitive
                if (event.getPersister().getPropertyType(tempFields[i].getName()).isEntityType() == false{
                    Map tempMap 
= new HashMap();
                    tempFields[i].setAccessible(
true);
                    tempMap.put(tempFields[i].getName(), tempFields[i].get(event.getEntity()));
                    tempList.add(tempMap);
                }
 else {
                    Class obj 
= event.getId().getClass();
                    Field[] objFields 
= obj.getDeclaredFields();
                    
for (int j = 0; j < objFields.length; j++{
                        
if (objFields[j].getName().equals("serialVersionUID")) {
                            
continue;
                        }

                        objFields[j].setAccessible(
true);
                        Map tempMap 
= new HashMap();
                        tempMap.put(objFields[j].getName(), objFields[j].get(event.getId()));
                        tempList.add(tempMap);
                    }


                }


                map.put(
"pkName", tempList);

            }

        }


        
// get new value
        StringBuffer buffer = new StringBuffer();

        
for (int i = 0; i < event.getState().length; i++{
            
if (false == buffer.toString().equals("")) {
                buffer.append(
",");
            }


            
// if collection or entity
            if (event.getPersister().getPropertyType(event.getPersister().getPropertyNames()[i]).isCollectionType()
                    
|| event.getPersister().getPropertyType(event.getPersister().getPropertyNames()[i]).isEntityType()) {
                
continue;
            }


            buffer.append(event.getPersister().getPropertyNames()[i]).append(
"=").append(event.getState()[i]);
        }


        map.put(
"afterproperty", buffer.toString());

        
return map;
    }


}

package com.core.util;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.event.spi.PostUpdateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * <p>
 * PostUpdateEventListiner.
 * </p>
 * 
 * 
@author liu_dawei
 
*/

@SuppressWarnings(
"rawtypes""unchecked""serial" })
public class PostUpdateEventListiner extends org.hibernate.ejb.event.EJB3PostUpdateEventListener {

    
private static final Logger logger = LoggerFactory.getLogger(PostUpdateEventListiner.class);

    
private enum OperationType {
        CREATE, UPDATE, DELETE
    }


    @Override
    
public void onPostUpdate(PostUpdateEvent event) {

        
try {
            Connection con 
= event.getSession().connection();

            Map map 
= getContent(event);

            PostSaveEventListener.getInstance().postOperation(con, map, OperationType.UPDATE.ordinal());
        }
 catch (Exception e) {
            logger.error(e.getMessage());
        }


    }


    
public Map getContent(PostUpdateEvent event) throws IllegalArgumentException, IllegalAccessException,
            InstantiationException, ClassNotFoundException 
{

        Map map 
= new HashMap();

        
// get table
        Serializable[] serializables = event.getPersister().getPropertySpaces();
        map.put(
"tableName", serializables[0]);

        
// get PK
        String identifierPropertyName = event.getPersister().getIdentifierPropertyName();

        Field[] tempFields 
= event.getEntity().getClass().getDeclaredFields();
        
for (int i = 0; i < tempFields.length; i++{
            
if (tempFields[i].getName().equals(identifierPropertyName)) {
                List tempList 
= new ArrayList();
                
// if PK is Primitive
                if (event.getPersister().getPropertyType(tempFields[i].getName()).isEntityType() == false{
                    Map tempMap 
= new HashMap();
                    tempFields[i].setAccessible(
true);
                    tempMap.put(tempFields[i].getName(), tempFields[i].get(event.getEntity()));
                    tempList.add(tempMap);
                }
 else {
                    Class obj 
= event.getId().getClass();
                    Field[] objFields 
= obj.getDeclaredFields();
                    
for (int j = 0; j < objFields.length; j++{
                        
if (objFields[j].getName().equals("serialVersionUID")) {
                            
continue;
                        }

                        objFields[j].setAccessible(
true);
                        Map tempMap 
= new HashMap();
                        tempMap.put(objFields[j].getName(), objFields[j].get(event.getId()));
                        tempList.add(tempMap);
                    }


                }


                map.put(
"pkName", tempList);

            }

        }


        
// get change date
        StringBuffer oldStateBuffer = new StringBuffer();
        StringBuffer newStateBuffer 
= new StringBuffer();
        
for (int i = 0; i < event.getState().length; i++{
            
// after
            Object oldValue = event.getOldState()[i];
            
// previous
            Object newValue = event.getState()[i];

            
if ((null == oldValue && null != newValue)
                    
|| (null != oldValue && null == newValue)
                    
|| (null != oldValue && null != newValue && false == oldValue.toString()
                            .equals(newValue.toString()))) 
{
                
if ((false == oldStateBuffer.toString().equals(""))) {
                    oldStateBuffer.append(
",");

                }

                
if ((false == newStateBuffer.toString().equals(""))) {
                    newStateBuffer.append(
",");

                }


                
// if collection or entity
                if (event.getPersister().getPropertyType(event.getPersister().getPropertyNames()[i]).isCollectionType()
                        
|| event.getPersister().getPropertyType(event.getPersister().getPropertyNames()[i])
                                .isEntityType()) 
{
                    
continue;
                }


                String propertyName 
= event.getPersister().getPropertyNames()[i];
                oldStateBuffer.append(propertyName).append(
"=").append(oldValue);
                newStateBuffer.append(propertyName).append(
"=").append(newValue);

            }


        }

        map.put(
"previousproperty", oldStateBuffer.toString());
        map.put(
"afterproperty", newStateBuffer.toString());

        
return map;

    }


}

package com.core.util;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.ejb.event.EJB3PostDeleteEventListener;
import org.hibernate.event.spi.PostDeleteEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * <p>
 * PostDeleteEventListener.
 * </p>
 * 
 * 
@author liu_dawei
 
*/

@SuppressWarnings(
"serial")
public class PostDeleteEventListener extends EJB3PostDeleteEventListener {

    
private static final Logger logger = LoggerFactory.getLogger(PostDeleteEventListener.class);

    
private enum OperationType {
        CREATE, UPDATE, DELETE
    }


    @SuppressWarnings(
"rawtypes")
    @Override
    
public void onPostDelete(PostDeleteEvent event) {

        
try {
            Connection con 
= event.getSession().connection();

            Map map 
= getContent(event);

            PostSaveEventListener.getInstance().postOperation(con, map, OperationType.DELETE.ordinal());
        }
 catch (Exception e) {
            logger.error(e.getMessage());
        }


    }


    @SuppressWarnings(
"rawtypes""unchecked" })
    
public Map getContent(PostDeleteEvent event) throws IllegalArgumentException, IllegalAccessException,
            InstantiationException, ClassNotFoundException 
{

        Map map 
= new HashMap();

        
// get table
        Serializable[] serializables = event.getPersister().getPropertySpaces();
        map.put(
"tableName", serializables[0]);

        
// get PK
        String identifierPropertyName = event.getPersister().getIdentifierPropertyName();

        Field[] tempFields 
= event.getEntity().getClass().getDeclaredFields();
        
for (int i = 0; i < tempFields.length; i++{
            
if (tempFields[i].getName().equals(identifierPropertyName)) {
                List tempList 
= new ArrayList();
                
// if PK is Primitive
                if (event.getPersister().getPropertyType(tempFields[i].getName()).isEntityType() == false{
                    Map tempMap 
= new HashMap();
                    tempFields[i].setAccessible(
true);
                    tempMap.put(tempFields[i].getName(), tempFields[i].get(event.getEntity()));
                    tempList.add(tempMap);
                }
 else {
                    Class obj 
= event.getId().getClass();
                    Field[] objFields 
= obj.getDeclaredFields();
                    
for (int j = 0; j < objFields.length; j++{
                        
if (objFields[j].getName().equals("serialVersionUID")) {
                            
continue;
                        }

                        objFields[j].setAccessible(
true);
                        Map tempMap 
= new HashMap();
                        tempMap.put(objFields[j].getName(), objFields[j].get(event.getId()));
                        tempList.add(tempMap);
                    }


                }


                map.put(
"pkName", tempList);

            }

        }


        
// get old value
        StringBuffer buffer = new StringBuffer();

        
for (int i = 0; i < event.getDeletedState().length; i++{
            
if (false == buffer.toString().equals("")) {
                buffer.append(
",");
            }


            
// if collection or entity
            if (event.getPersister().getPropertyType(event.getPersister().getPropertyNames()[i]).isCollectionType()
                    
|| event.getPersister().getPropertyType(event.getPersister().getPropertyNames()[i]).isEntityType()) {
                
continue;
            }


            buffer.append(event.getPersister().getPropertyNames()[i]).append(
"=").append(event.getDeletedState()[i]);
        }


        map.put(
"previousproperty", buffer.toString());

        
return map;
    }


}




 
posted on 2012-11-01 11:28 孤飞燕 阅读(5178) 评论(0)  编辑  收藏 所属分类: Hibernate||JPA

只有注册用户登录后才能发表评论。


网站导航: