Java Reference
In-Depth Information
@SuppressWarnings("unchecked")
public
T findBy(String fieldName, Object value) {
Query query = Stripersist.getEntityManager()
.createQuery(getQuery(fieldName,
null
))
.setParameter(fieldName, value);
return
getSingleResult(query);
}
@SuppressWarnings("unchecked")
public
T findBy(String fieldName, Object value, User user) {
Query query = Stripersist.getEntityManager()
.createQuery(getQuery(fieldName, user))
.setParameter(fieldName, value)
.setParameter("user", user);
return
getSingleResult(query);
}
private
String getQuery(String fieldName, User user){
String query =
"from " + entityClass.getName() + " t " +
"where t." + fieldName + " = :" + fieldName;
if
(user ==
null
) {
return
query;
}
return
query + " and t.user = :user";
}
@SuppressWarnings("unchecked")
private
T getSingleResult(Query query) {
try
{
return
(T) query.getSingleResult();
}
catch
(NonUniqueResultException exc) {
return
(T) query.getResultList().get(0);
}
catch
(NoResultException exc) {
return null
;
}
}
These two
findBy
( ) methods find an object according to a specified field.
Unlike the first method, the second method constrains the search to
a specific user. Both methods use a query constructed with the JPA
query syntax, which looks similar to SQL but supports, among other
things, named parameters that start with a colon (:).
With this code in the base DAO, it's now very easy to implement the
subclasses by extending the base and implementing the methods de-
fined in each specific DAO interface. For example, remember that the
ContactDao
interface added the
findByEmail
( ) method.
Search WWH ::
Custom Search