Hibernate:执行getHibernateTemplate()。update query时的MappingException

时间:2011-12-14 16:29:27

标签: hibernate exception mapping

有例外原因:

org.hibernate.MappingException: Unknown entity: UserDetails set confirmed=true where username=? and confirmationCode=?

执行此代码时:

public void confirmUser(String username,String confirmationCode){
    getHibernateTemplate().update("UserDetails set confirmed=true where username=? and confirmationCode=?",new Object[]{username,confirmationCode});
}

修改

This query works OK:
    public String getUserMail(String username) {
        return (String) DataAccessUtils.uniqueResult(getHibernateTemplate().find(
                "select mail from UserDetails where username=?", new Object[] { username }));
    }

这意味着我的hbm.xml也应该没问题:

<hibernate-mapping>
    <class name="model.UserDetails" table="users">
        <id name="id">
            <generator class="increment"/>
        </id>
        <property name="username" column="username"/>
        <property name="password" column="password"/>
        <property name="enabled" column="enabled"/>
        <property name="mail" column="mail"/>
        <property name="city" column="city"/>
        <property name="confirmed" column="confirmed"/>
        <property name="confirmationCode" column="confirmation_code"/>

        <set name="authorities" cascade="all" inverse="true">
            <key column="id" not-null="true"/>
            <one-to-many class="model.Authority"/>
        </set>

    </class>
</hibernate-mapping>

问题是,如何使用参数集执行update方法,因为getHibernateTemplate().update假定将Object传递给方法,而不是SQL查询。

1 个答案:

答案 0 :(得分:0)

为了通过Hibernate ORM执行更新,我使用了这样的结构:

SessionFactory sf = getHibernateTemplate().getSessionFactory();
Session s = sf.openSession();
Query q = s.createQuery("UserDetails set confirmed=true
 where username:username and confirmationCode=:confirmationCode");
q.setString("username", username);
q.setString("confirmationCode", confirmationCode);
q.executeUpdate();

由于getHibernateTemplate().update不允许命名参数,因此完成了。
应该有对象通过。

相关问题