简体   繁体   中英

HQL Login with username and email from two different tables

I have Form with inputs username and password to login my app.

This is my query:

public LoginUsr logInUsr(RequestLoginUsr request) {
         List<User> l = getCurrentSession()
         .createQuery("from User where name = :username and pass = :password")
         .setParameter("username", request.getUsername())
         .setParameter("password", request.getPassword())
         .getResultList();

      if(l.size() == 1) {
         User u = l.get(0);
         return new LoginUsr(u.getSurname(),u.getId(),u.getFkUsrPrc(), null);
      } else {
         return null;
      }
   }

RequestLoginUsr:

public class RequestLoginUsr {
   private String username;
   private String password;
   private Integer moduleId;
   private Integer computerId;
}

It's working but...

Now I would add possibility then input name was also email from second table 'ContactPerson' on the same input.

This is code but not work:

FROM User as usr JOIN ContactPerson ctp on usr.name = :username 
AND usr.pass = :password OR ctp.email = :username

How can I do this?

I need login to my app with parameter name from User table or email from ContactPerson table.

Please consider to re-write your query in this way:

But I suppose you have in ContactPerson class a referral to User class (as many-to-one or a simple foreign key property)

FROM User as usr 
WHERE usr.pass = :password
AND (usr.name = :username 
    OR EXISTS
       (SELECT 1 FROM ContactPerson ctp WHERE ctp.email = :username
       AND ctp.user = usr)
)

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