1

As per the Documentation we can specify named queries in an XML. But it does not tell how to use it in the code. Can someone please help?

sidgate
  • 14,650
  • 11
  • 68
  • 119

3 Answers3

3
say you have defined the `Named Query` as `application.myquery` in XML file.

In service/dao layer

List results = em.createNamedQuery("application.myquery")
    .setParameter("username", "blah")
    .setParameter("password","blahblahblah")
    .getResultList();

The orm file need to be included inside persistence.xml and the same should reside at META-INF/persistence.xml.

<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">

  <persistence-unit name="myUnit" transaction-type="RESOURCE_LOCAL">
    <mapping-file>META-INF/orm.xml</mapping-file>
    <exclude-unlisted-classes/>
  </persistence-unit>

</persistence>

Refer this for more info.

Ankur Singhal
  • 26,012
  • 16
  • 82
  • 116
  • Thanks for the input. I tried this out but getting the error that the named query not found. Looks like the XML file is not getting loaded. Where should XML file reside? I tried it in META-INF – sidgate Jul 24 '14 at 14:23
3

As is mentioned by the lead developer of Spring Data JPA here, all you need to do (if you are using a version newer or equal to Spring Data JPA 1.5 - I tested with 1.6.1.RELEASE) is add a method in the repository with the same name as the query.

For example you could have code like:

    @Entity
    @NamedQuery(name = "User.findByLastname", query="select u from User u where u.lastname = ?1")
    public class User {
       //whatever
    }

If you don't want to use annotations but prefer XML instead, you need to add

<named-query name="User.findByLastname">
  <query>select u from User u where u.lastname = ?1</query>
</named-query>

to orm.xml like is shown here

Finally the repository would look like

public interface UserRepository extends CrudRepository<User, Long> {

  @Query
  List<User> findByLastname(String lastname);
}
Community
  • 1
  • 1
geoand
  • 60,071
  • 24
  • 172
  • 190
1

META-INF/orm.xml

<?xml version="1.0" encoding="UTF-8"?>
<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm http://java.sun.com/xml/ns/persistence/orm_2_0.xsd"
    version="2.0">

    <named-query name="Role.findByCond">
        <query>from Role where rid = ?1 and rname = ?2</query>
    </named-query>

</entity-mappings>

RoleRepository.java

@Query
List<Role> findByCond(String rid, String rname);
lionyu
  • 593
  • 3
  • 5
  • 14