public <T> T getSingleEntityByParameter(Class entityClass, String fieldName, Object parameter) { TypedQuery<T> query = PersistenceHelper.getQuery("from " + entityClass.getName() + " s where s." + fieldName + "=:param", entityClass); query.setParameter("param", parameter); query.setMaxResults(1); List<T> entities = query.getResultList(); if (!entities.isEmpty()) { return entities.get(0); } return null; } 

Can I write better?

  • possible without criteria =) - Gorets
  • Well, this is without criteria (although I don’t understand why everyone does not like them so much). I don’t like here how I set the class, and how to choose one result from the returned sheet. and getSingleResult (), as you know, throws various exceptions .. - KutaBeach

0