简体   繁体   中英

Hibernate entity with two unique keys using @NaturalId

I need a User entity that has a primary key ID and two unique not null (not primary) keys: email and username. Then I receive a username and an email and I need to retrieve a User entity that has either that received username or email.

I see that @NaturalId makes a column unique and not null. The problem is that when you have more than one @NaturalId, Hibernate creates a unique index on the pair (email, username), meaning that it won't be any rows with same pair (email, username) but it may appear one that has same email but different username.

Can it be solved with @NaturalId? If is possible how would I retrieve the entity matching either the received username or email but not necessarily both.

If it's not possible, would this be the optimal solution?

 final Session session = HibernateUtil.openSession();
 final CriteriaBuilder builder = session.getCriteriaBuilder();
 final CriteriaQuery<User> criteria = builder.createQuery(User.class);
 final Root<User> userRoot = criteria.from(User.class);

 criteria.where(builder.equal(userRoot.get("username"), username));
 /* How do I join the criteria for username and email using ||?
 So that it gets me an entity that has that email or username. */

 final User foundUser = session.createQuery(criteria).uniqueResult();

your query will like:

  Session session = HibernateUtil.getSession();
    Criteria criteria = session.createCriteria(User.class);
    criteria.add(Restrictions.disjunction()
                    .add(Restrictions.eq("username", value))
                    .add(Restrictions.eq("email", value)));
    User user = (User)criteria.setMaxResults(1).uniqueResult();

Hql query :

 Query query = session.createQuery("from User as s where s.username = :userInputValue or s.email =:userInputValue");
        query.setParameter("userInputValue", userInputValue);
        query.setMaxResults(1);
        User user = (User) query.uniqueResult();

you can't get unique result with your given result, because as you have mentioned, it may possible we have 2 rows which one of them have a username like "Jom@test.com" and another row have email "Jom@test.com". So it's possible scenario to not get unique value, for fix it you need make a 2 unique constraint of any of filed, basically you need 2 unique filed in one row.

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