简体   繁体   English

休眠和字符串主键,区分大小写的负载

[英]Hibernate and String primary key, case sensed load

I have a tlogin table in my DB which has got a primary key of String type, called Login . 我的数据库中有一个tlogin表,该表具有String类型的主键,称为Login This key is not generated by Hibernate authomatically, as it is assigned by the application. 该密钥不是由Hibernate合法生成的,因为它是由应用程序分配的。 Here it is the mapping: 这是映射:

<id name="_Login" column="Login" unsaved-value="null">
    <generator class="assigned" />
</id>

My problem comes when user logs in the application. 用户登录应用程序时出现我的问题。 Hibernate get and load methods seem to return an object with the key that user has typed into the log in form. Hibernate的getload方法似乎返回一个具有用户已在登录表单中键入的键的对象。 I'm trying the following code: 我正在尝试以下代码:

@Override
public CLogin loadLogin(String userName) throws AccessException {
    try {
        Session sesion = this._dao.init();
        CLogin login = (CLogin) sesion.get(CLogin.class, userName);
        return login;
    } catch (HibernateException e) {
        throw new AccessException(e.getMessage(), e);
    }
}

Here for example even the username is stored as example@hotmail.com in the DB, if the end user logs with EXAMPLE@hotmail.com , it will retrieve the object from the DB, but with EXAMPLE@hotmail.com key. 例如,在这里,甚至用户名都以example@hotmail.com的形式存储在数据库中,如果最终用户使用EXAMPLE@hotmail.com登录,它将从数据库中检索对象,但使用EXAMPLE@hotmail.com密钥。 I want to permit the user access the app, but I want to get his username as it is stored in the DB. 我想允许用户访问该应用程序,但是我想获取其用户名,因为该用户名存储在数据库中。

Do I have to implement a criteria for that? 我必须为此执行标准吗?

I would personally go for (as a namedQuery) 我个人会去(作为namedQuery)

SELECT * FROM `table` WHERE LOWER(`Login`) = LOWER("EXAMPLE@hotmail.com")

but there are other ways. 但是还有其他方法。

See MySQL case insensitive select 参见MySQL不区分大小写的选择

I finally achieved to solve it using an Hibernate Criteria. 我终于实现了使用休眠标准解决该问题的方法。 I use an ilike restriction which is an insensitive type of like , in addition to MatchMode.Exact , which allows to filter only the exact matches. 除了MatchMode.Exact ,我还使用了ilike限制,它是like的不敏感类型, MatchMode.Exact允许过滤完全匹配的内容。

That's how it works: 这就是它的工作方式:

public CLogin loadLogin(String userName) throws AccessException {
        try {
            Session sesion = this._dao.init();
            CLogin login = (CLogin) sesion.createCriteria(CLogin.class).add(
                    Restrictions.ilike("_Login", userName.toLowerCase(), MatchMode.EXACT))
                    .uniqueResult();
            if (login == null) {
                throw new AccessException("User does not exist");
            }
            return login;
        } catch (HibernateException e) {
            throw new AccessException(e.getMessage(), e);
        }
    }

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

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