It sounds like you want to match a given username to either a Customer
or a Merchant
. Since the two tables are unrelated, to do this with a single query, I believe you would need to form a cartesian product (join every row of one table with every row in the other). As you might imagine, this could be very inefficient. You're better off doing two simple queries:
try {
Customer c = em.createQuery("SELECT c FROM Customer c WHERE c.username = :username", Customer.class)
.setParameter("username", username)
.getSingleResult();
// ... do something with the customer ...
} catch (NoResultException e) {
// user wasn't found in the customer table, try merchant:
try {
Merchant m = em.createQuery("SELECT m FROM Merchant m WHERE m.username = :username", Merchant.class)
.setParameter("username", username)
.getSingleResult();
// ... do something with the merchant ...
} catch (NoResultException e) {
// user wasn't found in either table
}
}
Note: I'm assuming that username
is unique within Customer
and Merchant
.
Notice that this approach will only execute the second query if we don't find the user with the first. If you don't need to return the object (i.e. just need to check if it exists) then you could simplify the above with two count queries. Count queries always return a result, so you wouldn't need to catch the NoResultException
s