Databases Reference
In-Depth Information
The declaration of our named native query looks like the following code snippet:
@Entity
@NamedNativeQueries({
@NamedNativeQuery(name = "Contact.findContacts",
query = "SELECT * FROM contacts c WHERE LOWER(c.
first_name) LIKE LOWER(:searchTerm) OR LOWER(c.last_name) LIKE
LOWER(:searchTerm)",
resultClass = Contact.class)
})
@Table(name = "contacts")
public class Contact
We can also use XML for creating named native queries. In this
case, we must use the
named-native-query
element and
declare the SQL query in an entity mapping XML file.
Creating the query method
Our next step is to add the query method to the contact repository. We will have to:
1.
Determine the correct name for the query method. Spring Data JPA resolves
method names back to named queries by pretending the simple name of
the managed entity and a dot to the method name. The name of our named
query is
Contact.findContacts
. Thus, we have to add a method called
findContacts
to the
ContactRepository
interface.
2.
Use the
@Param
annotation to identify the method parameter as a value of the
named parameter that is used in our queries.
The signature of the added query method is given as follows:
public List<Contact> findContacts(@Param("searchTerm") String
searchTerm);
Creating the service method
Next we have to add the
search()
method to the
RepositoryContactService
class.
Our implementation consists of the following steps:
1.
We build the used like pattern.
2.
We fetch the search results by calling the created query method.