title: How to update Entity in TimerTask in Hibernate
body: <p>I want to update an Entity Field after 2min (10sec in the code below for testing). The code runs without any exception and the message there is printed but the entity is not really updated. What may be the problem?
  Here's the code I used: </p>
  
  <pre><code> @Transactional
  public void scheduleTimer(UserSMSEntity userSMSEntity) {
      Timer timer = new Timer();
      TimerTask timerTask = new TimerTask() {
          @Override
          @Transactional
          public void run() {
              userSMSEntity.lastSMSCode = -1;
              update(userSMSEntity);
              System.out.println("TIMER TASK");
          }
      };
      timer.schedule(timerTask, 10000);
  }
  </code></pre>
  
  <p>and here's the code for "update" method:</p>
  
  <pre><code>@Transactional
  public void update(T entity) {
      entity.setLastModificationDate(new Date());
      entityManager.merge(entity);
      logger.debug(entity.toString() + " Updated!");
  }
  </code></pre>
  
  <p>EDIT :
  I fixed it using bellow code inside the Timer Task</p>
  
  <pre><code> Session session = sessionFactory.openSession();
              session.beginTransaction();
              UserSMSEntity userSMSEntity = getEntityByUserId(userId);
              UserSMSEntity userSMSEntity1 = entityManager.find(UserSMSEntity.class, userSMSEntity.getId());
              userSMSEntity1.lastSMSCode = -1;
              session.update(userSMSEntity1);
              session.getTransaction().commit();
              session.close();
  </code></pre>
  
  <p>here's how I used sessionFactory with autowired  :</p>
  
  <pre><code>@Autowired
   SessionFactory session;
  </code></pre>
  
  <p>and in applicationContext I Declared a Bean as bellow :</p>
  
  <pre><code> &lt;bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"&gt;
      &lt;property name="dataSource" ref="moduleDataSource" /&gt;
      &lt;property name="hibernateProperties"&gt;
          &lt;props&gt;
  
              &lt;prop key="hibernate.hbm2ddl.auto"&gt;update&lt;/prop&gt;
              &lt;prop key="hibernate.dialect"&gt;org.hibernate.dialect.MySQL5Dialect&lt;/prop&gt;
          &lt;/props&gt;
      &lt;/property&gt;
  
  
      &lt;property name="packagesToScan"
                value="you package"/&gt;
  &lt;/bean&gt;
  </code></pre>