-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 posts ] 
Author Message
 Post subject: Pre[Update|Insert]EventListener kicks in too late?
PostPosted: Thu Jun 12, 2008 5:26 am 
Newbie

Joined: Thu Nov 10, 2005 4:24 am
Posts: 8
Need help with Hibernate? Read this first:
http://www.hibernate.org/ForumMailingli ... AskForHelp

Hibernate version:
<hibernate.core.version>3.2.6.ga</hibernate.core.version>
<hibernate-annotations.version>3.3.1.GA</hibernate-annotations.version>


Mapping documents:
annotations

Code between sessionFactory.openSession() and session.close():
handled by AbstractTransactionalTestNGSpringContextTests

Sessionfactory config:

Quote:
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">

<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle9iDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.cache.use_second_level_cache">true</prop>
<prop key="hibernate.cache.use_query_cache">true</prop>
<prop key="hibernate.generate_statistics">true</prop>
<prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>
<prop key="hibernte.cache.provider_configuration_file_resource_path">classpath*:ehcache.xml</prop>
</props>
</property>
<property name="dataSource" ref="dataSource"/>
<!--<property name="entityInterceptor" ref="auditInterceptor"/>-->
<property name="eventListeners" >
<map>
<!-- @see org.hibernate.event.EventListeners#eventInterfaceFromType -->

<entry key="pre-update" value-ref="metaDataListener" />
<entry key="pre-insert" value-ref="metaDataListener" />

<entry key="create" value-ref="metaDataListener" />
</map>
</property>

<!-- let hibernate scan all these packages for persistent classes! -->
<property name="annotatedClasses">
<list>

<value>eu.europa.ec.digit.systat2.security.User</value>
</list>
</property>

</bean>

<bean id="metaDataListener" class="eu.europa.ec.digit.systat2.util.model.MetaDataListener" scope="singleton" />


this is the metadatalistener:

Code:
public class MetaDataListener implements PreUpdateEventListener, PreInsertEventListener, PersistEventListener {

    private static final Logger log = Logger.getLogger(MetaDataListener.class);

    public MetaDataListener() {
        log.info("metadatalistener created");
    }

    @PrePersist
    public void setCreation(Object o) {
        log.debug("metadatalistener .setCreation");
        DataBaseMeta data = getMetaDataFromObject(o);
        if (data != null) {
            data.setDateCreat(getCurrentTime());
            data.setUserCreat(SecurityUtilities.getCurrentUser());
            data.setDateModif(data.getDateCreat());
            data.setUserModif(data.getUserCreat());
            if (log.isDebugEnabled()) {
                log.debug(data.toString());
            }
        }
    }

    @PreUpdate
    public void setModification(Object o) {
        log.debug("metadatalistener .setModification");
        DataBaseMeta data = getMetaDataFromObject(o);

        if (data != null) {
            data.setDateModif(getCurrentTime());
            data.setUserModif(SecurityUtilities.getCurrentUser());
            if (log.isDebugEnabled()) {
                log.debug(data.toString());
            }             
        }
    }

    private DataBaseMeta getMetaDataFromObject(Object o) {
        DataBaseMeta data = null;
        try {
            BaseObject obj = (BaseObject) o;
            data = obj.getMetaData();
            if(data == null) {
                data = new DataBaseMeta();
                obj.setMetaData(data);
                log.warn("metadatalistener .getMetaDataFromObject metadata created!");
            }
        } catch (Exception e) {
            log.error("MetaDataListener could not extract metadata from object!", e);
        }
        return data;
    }

    private Date getCurrentTime() {
        return new Date();
    }

    /**
     * Return true if the operation should be vetoed
     */
    public boolean onPreUpdate(PreUpdateEvent event) {
        log.debug("metadatalistener .onPreUpdate");
        setModification(event.getEntity());
        return false;
    }

    /**
     * Return true if the operation should be vetoed
     */
    public boolean onPreInsert(PreInsertEvent event) {
        log.debug("metadatalistener .onPreInsert");
        setCreation(event.getEntity());
        return false;
    }

    /**
     * Handle the given create event.
     *
     * @param event The create event to be handled.
     * @throws org.hibernate.HibernateException
     */
   public void onPersist(PersistEvent event) throws HibernateException{                   
        log.debug("metadatalistener .onPersist(event)");
        setCreation(event.getObject());
    }

    /**
     * Handle the given create event.
     *
     * @param event The create event to be handled.
     * @throws HibernateException
     */
   public void onPersist(PersistEvent event, Map createdAlready) throws HibernateException{
        log.debug("metadatalistener .onPersist(event, map)");
        setCreation(event.getObject());
    }


}



Full stack trace of any exception that occurs:

Quote:
user0_.per_id=?
Hibernate:
select
SY2_SEQ_USR.nextval
from
dual
DEBUG MetaDataListener - metadatalistener .onPreInsert
DEBUG MetaDataListener - metadatalistener .setCreation
WARN MetaDataListener - metadatalistener .getMetaDataFromObject metadata created!
DEBUG MetaDataListener - dateCreat = Thu Jun 12 10:43:21 CEST 2008
,userCreat = opsomgu
,dateModif = Thu Jun 12 10:43:21 CEST 2008
,userModif = opsomgu
Hibernate:
insert
into
sy2_user
(date_creat, date_modif, util_creat, util_modif, birth_date, birth_last_name, first_name, first_name_2, first_na
me_3, first_name_4, job_id_1, job_id_2, userid, email, per_id, sex_cd, org_id_sp2_1, org_id_sp2_2, no_sysper, usual_last
_name, viewing_last_name, usr_id)
values
(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
WARN JDBCExceptionReporter - SQL Error: 1400, SQLState: 23000
ERROR JDBCExceptionReporter - ORA-01400: impossible d'insΘrer NULL dans ("APP_SYSTAT_D"."SY2_USER"."DATE_CREAT")

WARN JDBCExceptionReporter - SQL Error: 1400, SQLState: 23000
ERROR JDBCExceptionReporter - ORA-01400: impossible d'insΘrer NULL dans ("APP_SYSTAT_D"."SY2_USER"."DATE_CREAT")

ERROR AbstractFlushingEventListener - Could not synchronize database state with session
org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:71)
at ... at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:110)
at org.testng.TestRunner.runWorkers(TestRunner.java:712)
at org.testng.TestRunner.privateRun(TestRunner.java:582)
at org.apache.maven.surefire.testng.TestNGDirectoryTestSuite.execute(TestNGDirectoryTestSuite.java:141)
at org.apache.maven.surefire.Surefire.run(Surefire.java:177)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
org.apache.maven.surefire.booter.SurefireBooter.main(SurefireBooter.java:997)
Caused by: java.sql.BatchUpdateException: ORA-01400: impossible d'insΘrer NULL dans ("APP_SYSTAT_D"."SY2_USER"."DATE_CRE
AT")
...


Name and version of the database you are using:
select * from v$version:

Oracle9i Enterprise Edition Release 9.2.0.8.0 - 64bit Production

The generated SQL (show_sql=true):

Debug level Hibernate log excerpt:

Quote:
DEBUG AbstractBatcher - preparing statement
DEBUG SequenceGenerator - Sequence identifier generated: 25
DEBUG AbstractBatcher - about to close PreparedStatement (open PreparedStatements: 1, globally: 1)
DEBUG AbstractBatcher - closing statement
DEBUG SequenceHiLoGenerator - new hi value: 25
DEBUG AbstractSaveEventListener - generated identifier: 1250, using strategy: org.hibernate.id.SequenceHiLoGenerator
DEBUG AbstractSaveEventListener - saving [eu.europa.ec.digit.systat2.security.User#1250]
DEBUG AbstractFlushingEventListener - flushing session
DEBUG AbstractFlushingEventListener - processing flush-time cascades
DEBUG AbstractFlushingEventListener - dirty checking collections
DEBUG AbstractFlushingEventListener - Flushing entities and processing referenced collections
DEBUG AbstractFlushingEventListener - Processing unreferenced collections
DEBUG AbstractFlushingEventListener - Scheduling collection removes/(re)creates/updates
DEBUG AbstractFlushingEventListener - Flushed: 1 insertions, 0 updates, 0 deletions to 1 objects
DEBUG AbstractFlushingEventListener - Flushed: 0 (re)creations, 0 updates, 0 removals to 0 collections
DEBUG Printer - listing entities:
DEBUG Printer - eu.europa.ec.digit.systat2.security.User{viewingLastName=null, sexCode=M, perId=155000, metaData=null, userId=1250, login=landepe, mailAddress=peter.van.landeghem@ec.europa.eu, jobId=null, usualLastName=Van Landeghem, firstName2=null, birthDate=12 juin 2008, firstName=Peter, firstName4=null, jobId2=null, firstName3=null, syserNbr=null, sp2OuId=null, birthLastName=Van Landeghem, fullName=null, sp2OuId2=null}
DEBUG AbstractFlushingEventListener - executing flush
DEBUG ConnectionManager - registering flush begin
DEBUG UpdateTimestampsCache - Pre-invalidating space [sy2_user]

DEBUG MetaDataListener - metadatalistener .onPreInsert
DEBUG MetaDataListener - metadatalistener .setCreation
WARN MetaDataListener - metadatalistener .getMetaDataFromObject metadata created!
DEBUG MetaDataListener - dateCreat = Thu Jun 12 11:07:41 CEST 2008
,userCreat = opsomgu
,dateModif = Thu Jun 12 11:07:41 CEST 2008
,userModif = opsomgu

DEBUG AbstractEntityPersister - Inserting entity: [eu.europa.ec.digit.systat2.security.User#1250]
DEBUG AbstractBatcher - about to open PreparedStatement (open PreparedStatements: 0, globally: 0)
DEBUG SQL -
insert
into
sy2_user
(date_creat, date_modif, util_creat, util_modif, birth_date, birth_last_name, first_name, first_name_2, first_name_3, first_name_4, job_id_1, job_id_2, userid, email, per_id, sex_cd, org_id_sp2_1, org_id_sp2_2, no_sysper, usual_last_name, viewing_last_name, usr_id)
values
(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
Hibernate:
insert
into
sy2_user
(date_creat, date_modif, util_creat, util_modif, birth_date, birth_last_name, first_name, first_name_2, first_name_3, first_name_4, job_id_1, job_id_2, userid, email, per_id, sex_cd, org_id_sp2_1, org_id_sp2_2, no_sysper, usual_last_name, viewing_last_name, usr_id)
values
(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
DEBUG AbstractBatcher - preparing statement
DEBUG AbstractEntityPersister - Dehydrating entity: [eu.europa.ec.digit.systat2.security.User#1250]

DEBUG TimestampType - binding null to parameter: 1
DEBUG TimestampType - binding null to parameter: 2
DEBUG StringType - binding null to parameter: 3
DEBUG StringType - binding null to parameter: 4

DEBUG DateType - binding '12 juin 2008' to parameter: 5



so, what I see is that my PreUpdateEventListener and PreInsertEventListener come too late or something.

I see the null values for the audit fields being set on the preparedstatement instead of the values of the toString().

I'm sure they are there... but metadata was null from the beginning and it seems the listeners come in when the map of properties to persist has already been built, is this possible.


I hope I have given enough information, If more info is needed I will provide it directly when asked (I just thought the post is already far too long for a quick read :)).

Thanks in advance!


[/code]


Top
 Profile  
 
 Post subject: Re: Pre[Update|Insert]EventListener kicks in too late?
PostPosted: Sun Nov 21, 2010 5:27 pm 
Newbie

Joined: Tue May 18, 2010 5:39 am
Posts: 19
I had the same problem and was able to solve it using Listeners. I describe this in my blog at http://anshuiitk.blogspot.com/2010/11/h ... event.html . Let me know in case you have any doubts which I can clarify after reading the post.

_________________
AG
http://anshuiitk.blogspot.com


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.