'findTop3NBy' query method is used to retrieve top N records that match given query.
Example 1: Get top 3 records that match given firstName
List<Employee> findTop3ByFirstName(String firstName);
Above snippet produce following select query.
select * from employee e where e.first_name={FIRST_NAME} limit 3
Example 2: Get top 3 records that match to given lastName
List<Employee> findTop3ByLastName(String lastName);
Above snippet produce following select query.
select * from employee e where e.last_name={LAST_NAME} limit 3
Example 3: Get top 3 records that match to given age or firstName
List<Employee> findTop3ByAgeOrFirstName(int age, String firstName);
Above snippet produce following select query.
select * from employee 3 where 3.age={AGE} or 3.first_name={FIRST_NAME} limit 3
Example 4: Select top 3 employees matches to given firstName in the descending order of their lastName
List<Employee> findTop3ByFirstNameOrderByLastNameDesc(String firstName);
Above snippet produce following select query.
select * from employee e where e.first_name={FIRST_NAME} order by e.last_name desc limit 3
Follow below step-by-step procedure to build complete working application.
Step 1: Create new maven project ‘find-top-n-records-demo’.
Step 2: Update pom.xml with maven dependencies.
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.sample.app</groupId>
	<artifactId>find-top-n-records-demo</artifactId>
	<version>1</version>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.4.0</version>
	</parent>
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
		<dependency>
			<groupId>com.h2database</groupId>
			<artifactId>h2</artifactId>
		</dependency>
	</dependencies>
</project>
Step 3: Create application.properties file under src/main/resources folder.
application.properties
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.sample.app</groupId> <artifactId>find-top-n-records-demo</artifactId> <version>1</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.4.0</version> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> </dependency> </dependencies> </project>
Step 4: Define Employee entity.
Employee.java
package com.sample.app.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "employee")
public class Employee {
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private int id;
	@Column(name = "first_name")
	private String firstName;
	@Column(name = "last_name")
	private String lastName;
	@Column(name = "age")
	private int age;
	@Column(name = "salary")
	private double salary;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = 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 int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public double getSalary() {
		return salary;
	}
	public void setSalary(double salary) {
		this.salary = salary;
	}
	public static EmployeeBuilder builder() {
		return new EmployeeBuilder();
	}
	public static class EmployeeBuilder {
		private Employee emp;
		public EmployeeBuilder() {
			emp = new Employee();
		}
		public EmployeeBuilder firstName(String firstName) {
			emp.setFirstName(firstName);
			return this;
		}
		public EmployeeBuilder lastName(String lastName) {
			emp.setLastName(lastName);
			return this;
		}
		public EmployeeBuilder age(int age) {
			emp.setAge(age);
			return this;
		}
		public EmployeeBuilder salary(double salary) {
			emp.setSalary(salary);
			return this;
		}
		public Employee build() {
			return emp;
		}
	}
	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append("Employee [id=").append(id).append(", firstName=").append(firstName).append(", lastName=")
				.append(lastName).append(", age=").append(age).append(", salary=").append(salary).append("]");
		return builder.toString();
	}
}
Step 5: Define EmployeeRepository interface.
EmployeeRepository.java
package com.sample.app.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import com.sample.app.entity.Employee;
public interface EmployeeRepository extends JpaRepository<Employee, Integer> {
	List<Employee> findTop3ByFirstName(String firstName);
	List<Employee> findTop3ByLastName(String lastName);
	List<Employee> findTop3ByAgeOrFirstName(int age, String firstName);
	List<Employee> findTop3ByFirstNameOrderByLastNameDesc(String firstName);
}
Step 6: Define main application class.
App.java
package com.sample.app;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import com.sample.app.entity.Employee;
import com.sample.app.repository.EmployeeRepository;
@SpringBootApplication
public class App {
	public static void main(String args[]) {
		SpringApplication.run(App.class, args);
	}
	public void printEmployees(Iterable<Employee> emps, String msg) {
		System.out.println(msg);
		for (Employee emp : emps) {
			System.out.println(emp);
		}
		System.out.println();
	}
	@Bean
	@Transactional
	public CommandLineRunner demo(EmployeeRepository employeeRepository) {
		return (args) -> {
			Employee emp1 = Employee.builder().firstName("Ram").lastName("Gurram").age(32).salary(100000.23).build();
			Employee emp2 = Employee.builder().firstName("Ram").lastName("Chelli").age(43).salary(60000).build();
			Employee emp3 = Employee.builder().firstName("Gopi").lastName("Battu").age(45).salary(1000000).build();
			Employee emp4 = Employee.builder().firstName("Ram").lastName("Srikanth").age(39).salary(60000).build();
			Employee emp5 = Employee.builder().firstName("Surendra").lastName("Sami").age(32).salary(100000.23).build();
			Employee emp6 = Employee.builder().firstName("Deeraj").lastName("Arora").age(41).salary(1000000.23).build();
			Employee emp7 = Employee.builder().firstName("Sailu").lastName("Ptr").age(31).salary(50000.23).build();
			Employee emp8 = Employee.builder().firstName("Loopa").lastName("Battu").age(32).salary(80000.23).build();
			Employee emp9 = Employee.builder().firstName("Ram").lastName("Zlam").age(33).salary(80000.23).build();
			employeeRepository.save(emp1);
			employeeRepository.save(emp2);
			employeeRepository.save(emp3);
			employeeRepository.save(emp4);
			employeeRepository.save(emp5);
			employeeRepository.save(emp6);
			employeeRepository.save(emp7);
			employeeRepository.save(emp8);
			employeeRepository.save(emp9);
			List<Employee> emps = employeeRepository.findAll();
			printEmployees(emps, "All the employees information");
			emps = employeeRepository.findTop3ByFirstName("Ram");
			printEmployees(emps, "Top 3 employees with firstName 'Ram'");
			emps = employeeRepository.findTop3ByLastName("Battu");
			printEmployees(emps, "Top 3 employees with lastName 'Battu'");
			emps = employeeRepository.findTop3ByAgeOrFirstName(32, "Ram");
			printEmployees(emps, "Top 3 employees with age 32 or firstName Ram");
			emps = employeeRepository.findTop3ByFirstNameOrderByLastNameDesc("Ram");
			printEmployees(emps, "Top 3 employees with name 'Ram' and order by lastName in descending order");
		};
	}
}
Total project structure looks like below.
Run App.java, you will see below messages in console.
All the employees information Employee [id=1, firstName=Ram, lastName=Gurram, age=32, salary=100000.23] Employee [id=2, firstName=Ram, lastName=Chelli, age=43, salary=60000.0] Employee [id=3, firstName=Gopi, lastName=Battu, age=45, salary=1000000.0] Employee [id=4, firstName=Ram, lastName=Srikanth, age=39, salary=60000.0] Employee [id=5, firstName=Surendra, lastName=Sami, age=32, salary=100000.23] Employee [id=6, firstName=Deeraj, lastName=Arora, age=41, salary=1000000.23] Employee [id=7, firstName=Sailu, lastName=Ptr, age=31, salary=50000.23] Employee [id=8, firstName=Loopa, lastName=Battu, age=32, salary=80000.23] Employee [id=9, firstName=Ram, lastName=Zlam, age=33, salary=80000.23] Top 3 employees with firstName 'Ram' Employee [id=1, firstName=Ram, lastName=Gurram, age=32, salary=100000.23] Employee [id=2, firstName=Ram, lastName=Chelli, age=43, salary=60000.0] Employee [id=4, firstName=Ram, lastName=Srikanth, age=39, salary=60000.0] Top 3 employees with lastName 'Battu' Employee [id=3, firstName=Gopi, lastName=Battu, age=45, salary=1000000.0] Employee [id=8, firstName=Loopa, lastName=Battu, age=32, salary=80000.23] Top 3 employees with age 32 or firstName Ram Employee [id=1, firstName=Ram, lastName=Gurram, age=32, salary=100000.23] Employee [id=2, firstName=Ram, lastName=Chelli, age=43, salary=60000.0] Employee [id=4, firstName=Ram, lastName=Srikanth, age=39, salary=60000.0] Top 3 employees with name 'Ram' and order by lastName in descending order Employee [id=9, firstName=Ram, lastName=Zlam, age=33, salary=80000.23] Employee [id=4, firstName=Ram, lastName=Srikanth, age=39, salary=60000.0] Employee [id=1, firstName=Ram, lastName=Gurram, age=32, salary=100000.23]
You can download complete working application from below link.
https://github.com/harikrishna553/springboot/tree/master/jpa/find-top-n-records-demo
 
  

No comments:
Post a Comment