简体   繁体   English

Hibernate示例查询格式错误

[英]Hibernate example query incorrectly formed

User.hbm.xml 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>

My data access function 我的数据访问功能

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;
    }
}

I am only passing two out of the 6 attributes of the User class(username and password). 我只传递了User类的6个属性中的两个(用户名和密码)。 But in the query it also checks for the admin field. 但是在查询中,它还会检查admin字段。 It works fine if i put an exclude("admin") to the criteria. 如果我将exclude(“ admin”)设置为标准,则效果很好。 I cant quite figure out why this is happening. 我无法弄清楚为什么会这样。

I found the issue. 我发现了问题。

The default value for char is '\'. char的默认值为'\\ u0000'。 The create criteria excludes the field only if the value is found to be null. 仅当发现该值为空时,创建条件才排除该字段。 If i change it to String, it works fine. 如果我将其更改为String,它会正常工作。

Given the mapping of the admin field, we can assume that it is of type boolean. 给定admin字段的映射,我们可以假定它的类型为boolean。 A boolean is either true of false, but never null. 布尔值为true或false,但绝不能为null。 Why would the value of this field not be part of the example? 为什么此字段的值不属于示例? Hibernate can't assume that false means "I want to ignore this field" and that true means "I want to find the users whose admin flag is true". Hibernate不能假设false表示“我想忽略此字段”,而true表示“我想查找admin标志为true的用户”。 You might very well look for the users whose admin flag is false. 您可能会很好地寻找admin标志为false的用户。

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

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