简体   繁体   English

使用@NaturalId具有两个唯一键的休眠实体

[英]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. 我需要一个具有主键ID和两个唯一的非空(非主)键的User实体:电子邮件和用户名。 Then I receive a username and an email and I need to retrieve a User entity that has either that received username or email. 然后,我收到一个用户名和一封电子邮件,我需要检索一个具有接收到的用户名或电子邮件的User实体。

I see that @NaturalId makes a column unique and not null. 我看到@NaturalId使列唯一且不为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. 问题是,当您有多个@NaturalId时,Hibernate会在该对(电子邮件,用户名)上创建一个唯一索引,这意味着它不会是同一对(电子邮件,用户名)的任何行,但可能会出现一个电子邮件相同但用户名不同。

Can it be solved with @NaturalId? 可以使用@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 : HQL查询:

 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". 您无法使用给定的结果获得唯一的结果,因为正如您已经提到的那样,可能我们有两行,其中一行的用户名如“ Jom@test.com”,另一行的电子邮件为“ 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. 因此,有可能无法获得唯一的值,要解决此问题,您需要对任何文件进行2个唯一约束,基本上,您需要在一行中包含2个唯一文件。

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

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