Hibernate示例查询错误地形成

时间:2013-11-19 07:10:41

标签: java hibernate

User.hbm.xml

<class name="dataAccess.User" table="USER" schema="PUBLIC" catalog="XYZ">
    <id name="userId" type="long">
        <column name="USER_ID" precision="10" scale="0" />
        <generator class="assigned" />
    </id>
    <property name="userName" type="string">
        <column name="USER_NAME" length="25" not-null="true" unique="true" />
    </property>
    <property name="emailId" type="string">
        <column name="EMAIL_ID" length="50" not-null="true" />
    </property>
    <property name="password" type="string">
        <column name="PASSWORD" length="50" not-null="true" />
    </property>
    <property name="admin" type="char">
        <column name="ADMIN" length="1" not-null="true" />
    </property>
    <property name="lastLoginTime" type="timestamp">
        <column name="LAST_LOGIN_TIME" length="23" />
    </property>

我的数据访问功能

public List findByExample(User instance) {
    log.debug("finding User instance by example");
    try {
        List results = sessionFactory.openSession()
                .createCriteria("dataAccess.User")
                .add(Example.create(instance)).list();
        System.out.println(results.size());
        log.debug("find by example successful, result size: "
                + results.size());
        return results;
    } catch (RuntimeException re) {
        log.error("find by example failed", re);
        throw re;
    }
}

我只传递了User类的6个属性中的两个(用户名和密码)。但在查询中它还会检查管理字段。如果我将排除(“admin”)放入标准,它工作正常。我无法弄清楚为什么会这样。

2 个答案:

答案 0 :(得分:2)

我发现了这个问题。

char的默认值是'\ u0000'。仅当发现值为null时,创建条件才会排除该字段。如果我将其更改为String,它可以正常工作。

答案 1 :(得分:0)

考虑到admin字段的映射,我们可以假设它是boolean类型。布尔值为true,但从不为null。为什么这个字段的值不是示例的一部分? Hibernate不能假设false表示“我想忽略这个字段”,而true表示“我想找到admin标志为true的用户”。您可能会很好地查找其admin标志为false的用户。