JPA: JOIN in JPQL

Join on one-to-many relation in JPQL looks as follows: select b.fname, b.lname from Users b JOIN b.groups c where c.groupName = :groupName When several properties are specified in select clause, result is returned as Object[]: Object[] temp = (Object[]) em.createNamedQuery(“…”) .setParameter(“groupName”, groupName) .getSingleResult(); String fname = (String) temp[0]; String lname = (String) temp[1]; By the … Read more

JPQL Like Case Insensitive

You can use the concat operator: @Query(“select u from User u where lower(u.name) like lower(concat(‘%’, ?1,’%’))”) public List<User> findByNameFree(String name); or with a named parameter: @Query(“select u from User u where lower(u.name) like lower(concat(‘%’, :nameToFind,’%’))”) public List<User> findByNameFree(@Param(“nameToFind”) String name); (Tested with Spring Boot 1.4.3)

How do I do a “deep” fetch join in JPQL?

The JPA spec does not allow aliasing a fetch join, but some JPA providers do. EclipseLink does as of 2.4. EclipseLink also allow nested join fetch using the dot notation (i.e. “JOIN FETCH a.bs.c”), and supports a query hint “eclipselink.join-fetch” that allows nested joins (you can specify multiple hints of the same hint name). In … Read more

JPA Native Query select and cast object

You might want to try one of the following ways: Using the method createNativeQuery(sqlString, resultClass) Native queries can also be defined dynamically using the EntityManager.createNativeQuery() API. String sql = “SELECT USER.* FROM USER_ AS USER WHERE ID = ?”; Query query = em.createNativeQuery(sql, User.class); query.setParameter(1, id); User user = (User) query.getSingleResult(); Using the annotation @NamedNativeQuery … Read more

Doing an “IN” query with Hibernate

The syntax of your JPQL query is incorrect. Either use (with a positional parameter): List<Long> ids = Arrays.asList(380L, 382L, 386L); Query query = em.createQuery(“FROM TrackedItem item WHERE item.id IN (?1)”); query.setParameterList(1, ids) List<TrackedItem> items = query.getResultList(); Or (with a named parameter): List<Long> ids = Arrays.asList(380L, 382L, 386L); Query query = em.createQuery(“FROM TrackedItem item WHERE item.id … Read more

IN-clause in HQL or Java Persistence Query Language

Are you using Hibernate’s Query object, or JPA? For JPA, it should work fine: String jpql = “from A where name in (:names)”; Query q = em.createQuery(jpql); q.setParameter(“names”, l); For Hibernate’s, you’ll need to use the setParameterList: String hql = “from A where name in (:names)”; Query q = s.createQuery(hql); q.setParameterList(“names”, l);

tech