Search This Blog

Wednesday, November 14, 2018

TypedQuery in JPA

Query query = em.createQuery('select p from Person p where name = :name', Person.class);
query.setParameter('name', name);
return (Person) query.getSingleResult();

A better type safe version is to use TypedQuery:

TypedQuery<Person> query = em.createQuery("select p from Person p where name = :name", Person.class);
query.setParameter("name", name);
return query.getSingleResult();

Or simply:

Person person=em.createQuery("select p from Person p where name = :name", Person.class).setParameter("name", name).getSingleResult();