简体   繁体   中英

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 . This key is not generated by Hibernate authomatically, as it is assigned by the application. 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. 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. 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)

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

but there are other ways.

See MySQL case insensitive select

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.

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

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