☰ See All Chapters |
Spring Data JPA Method Naming Conventions for Query
Spring data JPA has its own naming conventions for methods. Following these conventions we can build sophisticated queries. These conventions are called also called as method name strategies. These strategies have defined set of keyword to use in method names. Based on the formed method name, method performs predefined operations. As a simple example:
public interface StudentRepository extends CrudRepository<Student, Long>{ List<Student> findByStudentId(Long studentId); List<Student> findByStudentIdLessThanAndMarksGreaterThan(Long studentId, Long marks); } @Service("studentService") public class StudentService { @Autowired private StudentRepository repository;
public void test() { List<Student> students1 = repository.findByStudentId(1L); students1.forEach(student1 -> System.out.println(student1));
List<Student> students2 = repository.findByStudentIdLessThanAndMarksGreaterThan(3L, 99L); students2.forEach(student2 -> System.out.println(student2)); } } |
This is an equivalent of below plain JPA
public class StudentService {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("StudentPU"); EntityManager em = emf.createEntityManager();
public void test(Long studentId) {
// Find students by studentId List<Student> students1 = findByStudentId(1L); students1.forEach(student1 -> System.out.println(student1));
// List all students whose studentId is less than and marks greater than List<Student> students2 = findByStudentIdLessThanAndMarksGreaterThan(3L, 99L); students2.forEach(student2 -> System.out.println(student2)); }
public List<Student> findByStudentId(Long studentId) {
em.getTransaction().begin(); Query q = em.createQuery("SELECT S FROM STUDENT S WHERE S.studentID = :studentID"); q.setParameter("studentID", studentId);
return (List<Student>) q.getResultList(); }
public List<Student> findByStudentIdLessThanAndMarksGreaterThan(Long studentId, Long marks) {
em.getTransaction().begin();
Query q = em.createQuery("SELECT S FROM STUDENT S WHERE S.studentID < :studentID AND S.marks > :marks"); q.setParameter("studentID", studentId); q.setParameter("studentID", marks); return (List<Student>) q.getResultList(); } } |
The following table shows Supported keywords inside method names
Keyword | Sample | JPQL snippet |
And | findByLastnameAndFirstname | … where x.lastname = ?1 and x.firstname = ?2 |
Or | findByLastnameOrFirstname | … where x.lastname = ?1 or x.firstname = ?2 |
Is Equals | findByFirstname findByFirstnameIs findByFirstnameEquals | … where x.firstname = ?1 |
Between | findByStartDateBetween | … where x.startDate between ?1 and ?2 |
LessThan | findByAgeLessThan | … where x.age < ?1 |
LessThanEqual | findByAgeLessThanEqual | … where x.age <= ?1 |
GreaterThan | findByAgeGreaterThan | … where x.age > ?1 |
GreaterThanEqual | findByAgeGreaterThanEqual | … where x.age >= ?1 |
After | findByStartDateAfter | … where x.startDate > ?1 |
Before | findByStartDateBefore | … where x.startDate < ?1 |
IsNull | findByAgeIsNull | … where x.age is null |
IsNotNull,NotNull | findByAge(Is)NotNull | … where x.age not null |
Like | findByFirstnameLike | … where x.firstname like ?1 |
NotLike | findByFirstnameNotLike | … where x.firstname not like ?1 |
StartingWith | findByFirstnameStartingWith | … where x.firstname like ?1(parameter bound with appended %) |
EndingWith | findByFirstnameEndingWith | … where x.firstname like ?1(parameter bound with prepended %) |
Containing | findByFirstnameContaining | … where x.firstname like ?1(parameter bound wrapped in %) |
OrderBy | findByAgeOrderByLastnameDesc | … where x.age = ?1 order by x.lastname desc |
Not | findByLastnameNot | … where x.lastname <> ?1 |
In | findByAgeIn(Collection<Age> ages) | … where x.age in ?1 |
NotIn | findByAgeNotIn(Collection<Age> ages) | … where x.age not in ?1 |
True | findByActiveTrue() | … where x.active = true |
False | findByActiveFalse() | … where x.active = false |
IgnoreCase | findByFirstnameIgnoreCase | … where UPPER(x.firstame) = UPPER(?1) |
Spring Data JPA Method Naming Conventions for Query Example
Now let us see one example how method naming conventions and strategies play a role in spring data JPA.
Database script (MySQL)
CREATE TABLE STUDENT ( STUDENTID INT NOT NULL AUTO_INCREMENT, FIRSTNAME VARCHAR(20) DEFAULT NULL, LASTNAME VARCHAR(20) DEFAULT NULL, MARKS INT(20) DEFAULT NULL, PRIMARY KEY (STUDENTID) );
INSERT INTO STUDENT (FIRSTNAME,LASTNAME,MARKS) VALUES ('Manu','Manjunatha', 100); INSERT INTO STUDENT (FIRSTNAME,LASTNAME,MARKS) VALUES('Advith','Tyagraj', 100); INSERT INTO STUDENT (FIRSTNAME,LASTNAME,MARKS) VALUES('Likitha','Tyagraj', 98);
COMMIT; |
pom.xml
<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.java4coding</groupId> <artifactId>QueryCreationFromMethodNames</artifactId> <version>0.0.1-SNAPSHOT</version>
<dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.1.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>5.1.4.RELEASE</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.4.1.Final</version> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-jpa</artifactId> <version>2.1.4.RELEASE</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.14</version> </dependency> </dependencies>
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> </project> |
persistence.xml
<?xml version="1.0" encoding="UTF-8"?> <persistence xmlns="https://java.sun.com/xml/ns/persistence" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://java.sun.com/xml/ns/persistence https://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" version="2.0">
<persistence-unit name="StudentPU"> <provider>org.hibernate.ejb.HibernatePersistence</provider> <properties> <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/study" /> <property name="hibernate.connection.driver_class" value="com.mysql.cj.jdbc.Driver" /> <property name="hibernate.connection.username" value="root" /> <property name="hibernate.connection.password" value="root" /> <property name="hibernate.archive.autodetection" value="class" /> <property name="hibernate.show_sql" value="true" /> <property name="hibernate.format_sql" value="true" /> <property name="hbm2ddl.auto" value="update" /> </properties> </persistence-unit> </persistence> |
Student.java
package com.java4coding;
import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id;
@Entity public class Student {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long studentId; private String firstName; private String lastName; private Long marks;
public Student() { super(); }
public Student(String firstName, String lastName, Long marks) { super(); this.firstName = firstName; this.lastName = lastName; this.marks = marks; }
//Setters and getters public Long getId() { return studentId; }
public void setId(Long id) { this.studentId = id; }
public String getFirstName() { return firstName; }
public void setFirstName(String firstName) { this.firstName = firstName; }
public String getLastName() { return lastName; }
public void setLastName(String lastName) { this.lastName = lastName; }
public Long getMarks() { return marks; }
public void setMarks(Long marks) { this.marks = marks; }
@Override public String toString() { return "Student [firstName=" + firstName + ", lastName=" + lastName + ", Marks= " + marks + "]"; } } |
AppConfig.java
package com.java4coding;
import javax.persistence.EntityManagerFactory;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.LocalEntityManagerFactoryBean;
@Configuration @EnableJpaRepositories(basePackages = {"com.java4coding"}) public class AppConfig { @Bean public LocalEntityManagerFactoryBean entityManagerFactory() { LocalEntityManagerFactoryBean factoryBean = new LocalEntityManagerFactoryBean(); factoryBean.setPersistenceUnitName("StudentPU");
return factoryBean; }
@Bean public JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) { JpaTransactionManager transactionManager = new JpaTransactionManager(); transactionManager.setEntityManagerFactory(entityManagerFactory);
return transactionManager; } } |
StudentRepository.java
package com.java4coding;
import java.util.List; import org.springframework.data.repository.CrudRepository;
public interface StudentRepository extends CrudRepository<Student, Long>{ List<Student> findByStudentId(Long studentId);
List<Student> findByStudentIdLessThanAndMarksGreaterThan(Long studentId, Long marks); } |
StudentService.java
package com.java4coding;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;
@Service("studentService") public class StudentService { @Autowired private StudentRepository repository;
public void test() { // Find students by studentId List<Student> students1 = repository.findByStudentId(1L); students1.forEach(student1 -> System.out.println(student1));
// List all students whose studentId is less than and marks greater than List<Student> students2 = repository.findByStudentIdLessThanAndMarksGreaterThan(3L, 99L); students2.forEach(student2 -> System.out.println(student2));
// Count number of customer long count = repository.count(); System.out.println("Number of students: " + count); } } |
Test.java
package com.java4coding;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Test { public static void main(String[] args) { AnnotationConfigApplicationContext appContext = new AnnotationConfigApplicationContext(); appContext.scan("com.java4coding"); appContext.refresh();
StudentService studentService = (StudentService) appContext.getBean("studentService"); studentService.test();
appContext.close(); } } |
Project directory structure
Output
Hibernate: select student0_.studentId as studentI1_0_, student0_.firstName as firstNam2_0_, student0_.lastName as lastName3_0_, student0_.marks as marks4_0_ from Student student0_ where student0_.studentId=? Student [firstName=Manu, lastName=Manjunatha, Marks= 100] Hibernate: select student0_.studentId as studentI1_0_, student0_.firstName as firstNam2_0_, student0_.lastName as lastName3_0_, student0_.marks as marks4_0_ from Student student0_ where student0_.studentId<? and student0_.marks>? Student [firstName=Manu, lastName=Manjunatha, Marks= 100] Student [firstName=Advith, lastName=Tyagraj, Marks= 100] Hibernate: select count(*) as col_0_0_ from Student student0_ Number of students: 3 |
All Chapters