简体   繁体   English

Hibernate saveorupdateall没有保存不更新

[英]Hibernate saveorupdateall not doing save not update

I have a spring integration hibernate application. 我有一个spring集成的hibernate应用程序。 My application picks up files and checks their entries against the database. 我的应用程序选择文件并根据数据库检查其条目。 For this i am using Hibernate. 为此,我正在使用Hibernate。

I want to disable certain rows in the database. 我想禁用数据库中的某些行。 I am retrieving the rows using criteria. 我正在使用条件检索行。 Editing one field and using saveorupdateall method. 编辑一个字段并使用saveorupdateall方法。 This is not changing my db rows at all!! 这根本不会改变我的数据库行!

Following are the code snippets 以下是代码片段

  <bean id="dmsdbDetectionJob" class="com.polling.scheduler.job.DMSDBDetectionJob">

 </bean>
 <bean id="dmsdbDetectionJobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
    <property name="targetObject" ref="dmsdbDetectionJob" />
    <property name="targetMethod" value="deleteDBMaster" />
    <property name="concurrent" value="false" />
 </bean>
<bean id="simpleTriggerDB" class="org.springframework.scheduling.quartz.CronTriggerBean">
    <property name="jobDetail" ref="dmsdbDetectionJobDetail" />
    <!-- <property name="cronExpression" value="1 * * * * ?" /> --> 
<!--    <property name="cronExpression" value="0 0/1 * * * ?" />  -->
    <property name="cronExpression" value="0 52 11 ? * *" />
 </bean>

This fires at given time properly. 这在正确的时间点火。 deleteDBMaster method calls this code: deleteDBMaster方法调用此代码:

        //get Document files not having any links
        List<DocumentFile> strayFiles = documentDaoImpl.getStrayDocumentFiles();
        try
        {
            if (strayFiles.size() > 0)
            {
                //delete
                strayFiles = documentDaoImpl.softDelete(strayFiles, DocumentFile.class);
                documentDaoImpl.saveOrUpdateAll(strayFiles);}
}...

The softDelete method uses generics softDelete方法使用泛型

    @Override
public <T extends GenericEntity> List<T> softDelete(List<T> stray,
        Class<T> clazz)
{
    for (T tObj : stray)
    {
        clazz.cast(tObj).setActive(Constants.INACTIVE.getVal());

    }
    return stray;
}

When I debug I see the value changed in the active property of the objects in the strayFiles list, inside saveOrUpdateAll() method. 当我调试时,我在saveOrUpdateAll()方法中看到strayFiles列表中对象的active属性中的值已更改。 The saveOrUpdateAll method is: saveOrUpdateAll方法是:

@Override
public void saveOrUpdateAll(Collection<?> objects) throws DMSException  {
    try {
        for (Object object : objects) {
            getCrntSession().saveOrUpdate(object);
        }
    } catch (final HibernateException e) {
        throw new DMSException("Exception while save or update All ", ErrorCode.BASE_DB_ERROR, e);
    }
} 

When the saveorupdate is called no query is logged by hibernate. 调用saveorupdate时,hibernate不会记录任何查询。 Nothing changes in the db!! db中没有任何变化!!

Since this is in spring integration I have just added a @Transactional to the method. 由于这是在spring集成中,我刚刚在方法中添加了@Transactional。 I am presuming that spring must do the flush or commit. 我假设spring必须执行flush或commit。 Is that wrong? 那是错的吗? And even then I should see the query right?? 即便如此,我应该看到查询正确?

Please let me know what is wrong in the code... 请让我知道代码中有什么问题......

Thanks 谢谢

EDIT:: 编辑::

Change my softdelete code to the following. 将我的softdelete代码更改为以下内容。 Thought maybe the generics are causing this. 想到也许仿制药正在造成这种情况。

    @Override
@Transactional
public void softDeleteDocumentFile(
        List<DocumentFile> stray)
{
    for (DocumentFile tObj : stray)
    {
        tObj.setActive(Constants.INACTIVE.getVal());
        saveEntity(tObj);
    }
}

Still no change. 仍然没有变化。 The rows are not getting updated. 行未更新。 Hibernate is not printing the update query on the console!! Hibernate没有在控制台上打印更新查询!!

Please let me know if anyone finds any mistake in the code.. 如果有人发现代码中有任何错误,请告诉我。

EDIT:: 编辑::

This is the configuration 这是配置

    <mvc:annotation-driven />

<context:component-scan base-package="com.polling" />
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>
     <context:property-placeholder location="classpath:config/jdbc.properties,classpath:config/config.properties,classpath:config/ftp.properties"/>
      <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource"
        >
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        </bean>
      <!-- Configure Hibernate 4 Session Factory -->
      <bean id="sessionFactory"
            class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">

            <property name="dataSource">
                  <ref bean="dataSource" />
            </property>

            <property name="hibernateProperties">
                  <props>
                        <prop key="hibernate.dialect">${hibernate.dialect}</prop>
                        <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
                        <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
                        <prop key="hibernate.generate_statistics">${hibernate.generate_statistics}</prop>
                  </props>
            </property>
            <property name="packagesToScan">
            <list>
                <value>com.polling.entity</value>
            </list>
        </property>
            </bean>
            <tx:annotation-driven />
<bean id="transactionManager"
    class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

EDIT:: 编辑::

Tried using a hardcoded id. 尝试使用硬编码的id。 Used update instead of save. 使用更新而不是保存。 But still same result, no update query and hence no change in row!! 但仍然是相同的结果,没有更新查询,因此行没有变化!

EDIT:: This is the log at trace level 编辑::这是跟踪级别的日志

    14:31:12.644 T|TransactionInterceptor                  |Completing transaction for [com.polling.service.DocumentServiceImpl.deActivateStrays]
14:31:12.644 T|TransactionInterceptor                  |Completing transaction for [com.polling.scheduler.job.DMSDBDetectionJob.deleteDBMaster]
14:31:12.675 T|HibernateTransactionManager             |Triggering beforeCommit synchronization
14:31:12.675 T|HibernateTransactionManager             |Triggering beforeCompletion synchronization
14:31:12.675 D|HibernateTransactionManager             |Initiating transaction commit
14:31:12.675 D|HibernateTransactionManager             |Committing Hibernate transaction on Session [SessionImpl(PersistenceContext[entityKeys=[EntityKey[com.polling.entity.DocumentFile#273], EntityKey[com.polling.entity.DocumentGroup#107], EntityKey[com.polling.entity.DocumentFile#275]],collectionKeys=[CollectionKey[com.polling.entity.DocumentFile.docgroups#275], CollectionKey[com.polling.entity.DocumentGroup.files#107], CollectionKey[com.polling.entity.DocumentFile.docgroups#273]]];ActionQueue[insertions=org.hibernate.engine.spi.ExecutableList@2a6f7180 updates=org.hibernate.engine.spi.ExecutableList@7a84a043 deletions=org.hibernate.engine.spi.ExecutableList@1935cd8c orphanRemovals=org.hibernate.engine.spi.ExecutableList@1b49af42 collectionCreations=org.hibernate.engine.spi.ExecutableList@291240d collectionRemovals=org.hibernate.engine.spi.ExecutableList@6d5d2cc collectionUpdates=org.hibernate.engine.spi.ExecutableList@40025295 collectionQueuedOps=org.hibernate.engine.spi.ExecutableList@587bd507 unresolvedInsertDependencies=UnresolvedEntityInsertActions[]])]
14:31:12.675 D|AbstractTransactionImpl                 |committing
14:31:12.675 T|SessionImpl                             |Automatically flushing session
14:31:12.675 T|AbstractFlushingEventListener           |Flushing session
14:31:12.675 D|AbstractFlushingEventListener           |Processing flush-time cascades
14:31:12.675 T|Cascade                                 |Processing cascade ACTION_SAVE_UPDATE for: com.polling.entity.DocumentFile
14:31:12.675 T|Cascade                                 |Done processing cascade ACTION_SAVE_UPDATE for: com.polling.entity.DocumentFile
14:31:12.675 T|Cascade                                 |Processing cascade ACTION_SAVE_UPDATE for: com.polling.entity.DocumentFile
14:31:12.675 T|Cascade                                 |Done processing cascade ACTION_SAVE_UPDATE for: com.polling.entity.DocumentFile
14:31:12.675 D|AbstractFlushingEventListener           |Dirty checking collections
14:31:12.675 T|AbstractFlushingEventListener           |Flushing entities and processing referenced collections
14:31:12.675 D|Collections                             |Collection found: [com.polling.entity.DocumentFile.docgroups#273], was: [com.polling.entity.DocumentFile.docgroups#273] (uninitialized)
14:31:12.691 D|Collections                             |Collection found: [com.polling.entity.DocumentFile.docgroups#275], was: [com.polling.entity.DocumentFile.docgroups#275] (uninitialized)
14:31:12.691 D|Collections                             |Collection found: [com.polling.entity.DocumentGroup.files#107], was: [com.polling.entity.DocumentGroup.files#107] (uninitialized)
14:31:12.691 T|AbstractFlushingEventListener           |Processing unreferenced collections
14:31:12.691 T|AbstractFlushingEventListener           |Scheduling collection removes/(re)creates/updates
14:31:12.691 D|AbstractFlushingEventListener           |Flushed: 0 insertions, 0 updates, 0 deletions to 3 objects
14:31:12.691 D|AbstractFlushingEventListener           |Flushed: 0 (re)creations, 0 updates, 0 removals to 3 collections
14:31:12.691 D|EntityPrinter                           |Listing entities:
14:31:12.691 D|EntityPrinter                           |com.polling.entity.DocumentFile{encodingKey=yyy, docgroups=<uninitialized>, contactNumber=12121212, documentType=com.polling.entity.DocumentType#5, totalLinks=1, modifiedBy=com.polling.entity.UserApplicationGroup#3, documentFileName=f11, documentDescription=null, totalDownloads=0, uploaderCompletePath=somepath/somepath, modifiedDate=2014-12-16 14:36:57.707, size=0, DMSPath=c:/DMSFinalRoot\dir0\File0, id=273, createdBy=com.polling.entity.UserApplicationGroup#3, documentFormat=com.polling.entity.DocumentFormat#1, uploadDateTime=2014-12-16 14:36:56.86, keyWords=null, active=3, uploadStage=1, uploaderIP=0:0:0:0:0:0:0:1, createdDate=2014-12-16 14:36:57.707, contactPerson=some name, uploaderName=scmsname}
14:31:12.691 D|EntityPrinter                           |com.polling.entity.DocumentGroup{files=<uninitialized>, expiryPresent=false, modifiedBy=com.polling.entity.UserApplicationGroup#3, uploadStatus=0, documentDescription=null, modifiedDate=2014-12-22 14:28:09.027, id=107, nodeId=206, totalFiles=0, createdBy=com.polling.entity.UserApplicationGroup#3, documentFormat=null, objectId=101, active=3, documentName=doc1, nodeType=document, objectType=demand, createdDate=2014-12-22 14:28:09.027, expiryAt=null}
14:31:12.691 D|EntityPrinter                           |com.polling.entity.DocumentFile{encodingKey=azaz, docgroups=<uninitialized>, contactNumber=12121212, documentType=com.polling.entity.DocumentType#5, totalLinks=1, modifiedBy=com.polling.entity.UserApplicationGroup#3, documentFileName=f11, documentDescription=null, totalDownloads=0, uploaderCompletePath=somepath/somepath, modifiedDate=2014-12-17 16:52:23.163, size=0, DMSPath=c:/DMSFinalRoot\dir2\File0, id=275, createdBy=com.polling.entity.UserApplicationGroup#3, documentFormat=com.polling.entity.DocumentFormat#1, uploadDateTime=2014-12-17 16:52:22.127, keyWords=null, active=9, uploadStage=1, uploaderIP=0:0:0:0:0:0:0:1, createdDate=2014-12-17 16:52:23.163, contactPerson=some name, uploaderName=scmsname}
14:31:12.691 T|AbstractFlushingEventListener           |Executing flush
14:31:12.691 T|JdbcCoordinatorImpl                     |Starting after statement execution processing [ON_CLOSE]
14:31:12.691 T|AbstractFlushingEventListener           |Post flush
14:31:12.691 T|SessionImpl                             |before transaction completion
14:31:12.691 D|JdbcTransaction                         |committed JDBC Connection
14:31:12.691 D|JdbcTransaction                         |re-enabling autocommit
14:31:12.691 T|TransactionCoordinatorImpl              |after transaction completion
14:31:12.707 T|SessionImpl                             |after transaction completion
14:31:12.707 T|HibernateTransactionManager             |Triggering afterCommit synchronization
14:31:12.707 T|HibernateTransactionManager             |Triggering afterCompletion synchronization
14:31:12.707 T|TransactionSynchronizationManager       |Clearing transaction synchronization
14:31:12.707 T|TransactionSynchronizationManager       |Removed value [org.springframework.orm.hibernate4.SessionHolder@711fbb66] for key [org.hibernate.internal.SessionFactoryImpl@5e2ed6a9] from thread [org.springframework.scheduling.quartz.SchedulerFactoryBean#0_Worker-7]
14:31:12.707 T|TransactionSynchronizationManager       |Removed value [org.springframework.jdbc.datasource.ConnectionHolder@67914078] for key [org.springframework.jdbc.datasource.DriverManagerDataSource@7bc247d0] from thread [org.springframework.scheduling.quartz.SchedulerFactoryBean#0_Worker-7]
14:31:12.707 D|HibernateTransactionManager             |Closing Hibernate Session [SessionImpl(PersistenceContext[entityKeys=[EntityKey[com.polling.entity.DocumentFile#273], EntityKey[com.polling.entity.DocumentGroup#107], EntityKey[com.polling.entity.DocumentFile#275]],collectionKeys=[CollectionKey[com.polling.entity.DocumentFile.docgroups#275], CollectionKey[com.polling.entity.DocumentGroup.files#107], CollectionKey[com.polling.entity.DocumentFile.docgroups#273]]];ActionQueue[insertions=org.hibernate.engine.spi.ExecutableList@2a6f7180 updates=org.hibernate.engine.spi.ExecutableList@7a84a043 deletions=org.hibernate.engine.spi.ExecutableList@1935cd8c orphanRemovals=org.hibernate.engine.spi.ExecutableList@1b49af42 collectionCreations=org.hibernate.engine.spi.ExecutableList@291240d collectionRemovals=org.hibernate.engine.spi.ExecutableList@6d5d2cc collectionUpdates=org.hibernate.engine.spi.ExecutableList@40025295 collectionQueuedOps=org.hibernate.engine.spi.ExecutableList@587bd507 unresolvedInsertDependencies=UnresolvedEntityInsertActions[]])] after transaction
14:31:12.707 T|SessionImpl                             |Closing session
14:31:12.707 I|StatisticalLoggingSessionEventListener  |Session Metrics {
    36322379 nanoseconds spent acquiring 1 JDBC connections;
    0 nanoseconds spent releasing 0 JDBC connections;
    16153296 nanoseconds spent preparing 2 JDBC statements;
    20467177 nanoseconds spent executing 2 JDBC statements;
    0 nanoseconds spent executing 0 JDBC batches;
    0 nanoseconds spent performing 0 L2C puts;
    0 nanoseconds spent performing 0 L2C hits;
    0 nanoseconds spent performing 0 L2C misses;
    7830765 nanoseconds spent executing 1 flushes (flushing a total of 3 entities and 3 collections);
    85953666 nanoseconds spent executing 2 partial-flushes (flushing a total of 2 entities and 2 collections)
}

Have found the crux of my problem. 找到了问题的症结所在。 Wasnt related to transactions at all. 根本不涉及交易。 By mistake I had added updatable=false to my entity class property(active) get accessor. 我错误地将updatable = false添加到我的实体类属性(活动)get访问器中。 Sorry for the trouble. 抱歉,添麻烦了。 Really a very elementary mistake!!! 真的是一个非常基本的错误! Apologies to all that have spent time on this.. 向所有花时间在这上面的人致歉

session.saveOrUpdate(Object) method only converts any transient object into persistence object, means object associates with current hibernate session. session.saveOrUpdate(Object)方法只将任何临时对象转换为持久对象,意味着对象与当前的hibernate会话关联。 When current hibernate session will be flushed or hibernate transaction will be committed then only actual query will run to store object data into the database. 当刷新当前的hibernate会话或提交hibernate事务时,只会运行实际的查询来将对象数据存储到数据库中。

Hibernate saveOrUpdate(Object) works like above comment. Hibernate saveOrUpdate(Object)的工作方式与上面的注释类似。 I don't know much about Spring. 我对Spring不太了解。 I hope above description will work for you. 我希望上面的描述对你有用。

Example code : Hibernate 示例代码:Hibernate

Session session = sessionFactory.getCurrentSession();
session.setFlush(FlushMode.COMMIT);// Session will be flushed when transation.commit will be called
Transaction tx = session.beginTransaction();
session.saveOrUpdate(Object obj);
tx.commit();// this line will run query to map your object on database

 OR

Session session = sessionFactory.getCurrentSession();
session.setFlush(FlushMode.MANUAL);// Session will be only ever flushed when session.flush() will be explicitely called by aaplication
Transaction tx = session.beginTransaction();
session.saveOrUpdate(Object obj);
session.flush();// this line will run query to map your object on database
tx.commit();

Thanks 谢谢

What you've written so far seems that your Spring TransactionManagement configuration is wrong. 到目前为止您所写的内容似乎是您的Spring TransactionManagement配置错误。

A simple solution if you don't want to configure aspects is to use a programmatic approach using the Spring Framework TransactionTemplate 如果您不想配置方面,一个简单的解决方案是使用Spring Framework TransactionTemplate的编程方法

public class DMSDBDetectionJob {

    private final TransactionTemplate transactionTemplate;

    public DMSDBDetectionJob(PlatformTransactionManager transactionManager) {
       Assert.notNull(transactionManager, "The 'transactionManager' argument must not be null.");
       this.transactionTemplate = new TransactionTemplate(transactionManager);
       // optional configuration of the Transaction like timeout
       // this.transactionTemplate.setTimeout(30); // 30 seconds
    }

    public void deleteDBMaster() {
      transactionTemplate.execute(new TransactionCallbackWithoutResult() {
          protected void doInTransactionWithoutResult(TransactionStatus status) {
             deleteDBMasterImpl();
         }
       });

    }

    private void deleteDBMasterImpl() {
        List<DocumentFile> strayFiles = documentDaoImpl.getStrayDocumentFiles();
        try
        {
           if (strayFiles.size() > 0)
           {
              //delete
              strayFiles = documentDaoImpl.softDelete(strayFiles, DocumentFile.class);
              documentDaoImpl.saveOrUpdateAll(strayFiles);
              ...
            }

         } catch (...) {...}
    }

Your Spring Configuration should have at least two entries like: 您的Spring配置至少应包含两个条目:

<!-- PlatformTransactionManager which are going to drive transaction-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  <property name="dataSource" ref="dataSource"></property>
</bean>

<!-- Instance of transaction template -->
<bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
  <property name="transactionManager" ref="transactionManager"></property>
</bean>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM