简体   繁体   中英

Hibernate getHibernateTemplate issue when saving object inside another object

I recently changed my code to make reference to the getHibernateTemplate(), and now my forms don't seem to save correctly, here's the code:


  public void saveForm(EcoFormFill form, int userId)
  throws RemoteException
  {
    User tmpUser = (User)getHibernateTemplate().load(User.class, new Integer(userId));
    form.setUser(tmpUser);
    getHibernateTemplate().saveOrUpdate(form);
  }

It complains that it can't set the 'user_id' to be null (a constraint in my DB)... Previously I was using this approach:


  public void saveForm(EcoFormFill form, int userId)
  throws RemoteException
  {
    Session ses = getHibernateTemplate().getSessionFactory().openSession();
    try
    {
      User tmpUser = (User) ses.load(User.class, new Integer(userId));
      form.setUser(tmpUser);
      ses.saveOrUpdate(form);
    }
    catch (Exception e)
    {
      log.error(e.getMessage(), e);
      throw new RemoteException(e.getMessage());
    }
    finally
    {
      ses.flush();
      ses.close();
    }
  }

And this approach works just fine, but it gives me grief with unit tests, so I need to use the previous approach with getHibernateTemplate().

Here's the association between my form and the user_id that is failing to populate:

<id name="id">
  <generator class="native"/>
</id>
...
...
<many-to-one column="user_id" name="user" not-null="false"/>

The SQL statements that are generated in both cases are identical except the fact that the user_id is not being inserted into the parameters properly.

Trevor is your application context seem to be like this

</bean>

<bean id="sessionFactory"
    class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="packagesToScan" value="yourRootPackage" />
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
            <prop key="hibernate.hbm2ddl.auto">create</prop>                
        </props>
    </property>
</bean>

<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
    <property name="sessionFactory" ref="sessionFactory"/>
</bean>


take look above, this part represent the minimum needed in your application context.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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