Posted on

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 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();
Leave a Reply

Your email address will not be published. Required fields are marked *