Help with Entity Query
neelixx Jan 29, 2006 4:14 PMBackground: I have a JSF application that queries for a User in the DB. If it can't find the user, it looks in Active Directory. If the User is in Active Directory, but not in the DB, it adds the user (persists), and returns it.
The problem is, the code never gets passed the entity query. If it can't find the user, it stops and returns null. The rest of my code never gets called.
At first, I thought it was because the query was throwing an EJBException, but surrounding the query in a try/catch clause didn't help.
Here is the method:
/** * This method integrates the DB and AD contexts for the User. It firsts checks whether * the user exists in the DB. If so, it returns the user. If not it then checks AD to see * if the user exists. If the user exists, but not in the DB, it adds it. * Returns a User object from the UPN supplied, provided the user exists in AD * @param String userPrincipleName * @returns User * @throws UserNotFoundException */ public User getUserByUPN(String upn) { User user = null; ADUserBean adUserBean; logger.debug("getting User from username: " + upn); // Let's try to get the user from the DB try { user = (User) em.createQuery("from User u where u.username=:upn") .setParameter("upn",upn) .getSingleResult(); } catch (EJBException e) { logger.debug("Could not find Entity in DB for user "+upn); } if (user != null) { logger.debug("Found " + upn + " in DB"); // user is in DB. No need to go any further. Return the DB user. return user; } else { // could not find user in the DB. This may be the first time the user // has been used in the system. Let's check AD to find out logger.debug("Could not find " + upn + " in the DB. Looking at Active Directory"); adUserBean = new ADUserBean(); user = adUserBean.getUserByUPN(upn); if (user != null) { //user exists in AD. Let's create a user object, save it to the DB //and return it logger.debug("Found user in Active Directory with username: " + upn); em.persist(user); return user; } } logger.debug("Could not find " + upn +". Returning Null"); return null; }
You can see the em.createQuery function, and I'm only interested in a single result. In my logs, you can clearly see that it did not find any rows in the result set. But, the rest of my code does not get called.
At the very least, the else clause of my if statement should have been called.
Am I using the createQuery() method incorrectly? Should I be using a different method?
Thanks!
Aaron