* BAEL-6063

* Updated the unit test class name

* Fixed the test

* Made updates to method names for tests and some refactor of code

* Updated the formatting using Baeldung formatter for Java

* Removed the space around = and made line continuations 2 spaces
This commit is contained in:
Muhammad Asif 2023-01-19 10:32:40 +05:00 committed by GitHub
parent fd1c286570
commit caa663239f
5 changed files with 223 additions and 0 deletions

View File

@ -0,0 +1,75 @@
package com.baeldung.spring.data.persistence.search;
import java.util.Objects;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
private int score;
public Student() {
}
public Student(String name, int score) {
this.name = name;
this.score = score;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", score=" + score + "]";
}
@Override
public int hashCode() {
return Objects.hash(id, name, score);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
return id == other.id && Objects.equals(name, other.name) && score == other.score;
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.spring.data.persistence.search;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class StudentApplication {
private static final Logger log = LoggerFactory.getLogger(StudentApplication.class);
public static void main(String[] args) {
SpringApplication.run(StudentApplication.class, args);
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung.spring.data.persistence.search;
import java.util.List;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface StudentRepository extends JpaRepository<Student, Long> {
Student findFirstByOrderByScoreDesc();
Student findFirstBy(Sort sort);
Student findFirstByNameLike(String name, Sort sort);
List<Student> findFirst3ByOrderByScoreDesc();
List<Student> findFirst2ByScoreBetween(int startScore, int endScore, Sort sort);
Student findTopByOrderByScoreDesc();
Student findTopBy(Sort sort);
Student findTopByNameLike(String name, Sort sort);
List<Student> findTop3ByOrderByScoreDesc();
List<Student> findTop2ByScoreBetween(int startScore, int endScore, Sort sort);
}

View File

@ -3,3 +3,4 @@ spring.datasource.username=sa
spring.datasource.password=sa
spring.jpa.properties.hibernate.globally_quoted_identifiers=true
logging.level.com.baeldung.spring.data.persistence.search=debug

View File

@ -0,0 +1,100 @@
package com.baeldung.spring.data.persistence.search;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Sort;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class StudentApplicationUnitTest {
@Autowired
private StudentRepository studentRepo;
private List<Student> students;
@Before
public void fillData() {
students = new ArrayList<>();
int count = 10;
Random r = new Random();
List<Integer> scores = r.ints(0, 101)
.distinct()
.limit(count)
.boxed()
.collect(Collectors.toList());
for (int i = 0; i < count; i++) {
Integer score = scores.get(i);
Student s = new Student("Student-" + i, score);
students.add(s);
}
studentRepo.saveAll(students);
Comparator<Student> c = Comparator.comparing(a -> a.getScore());
c = c.reversed();
students.sort(c);
}
@After
public void clearData() {
studentRepo.deleteAll();
}
@Test
public void givenStudentScores_whenMoreThanOne_thenFindFirst() {
Student student = studentRepo.findFirstByOrderByScoreDesc();
Student s = students.get(0);
assertEquals(student, s);
}
@Test
public void givenStudentScores_whenMoreThan3_thenFindFirstThree() {
List<Student> firstThree = studentRepo.findFirst3ByOrderByScoreDesc();
List<Student> sList = students.subList(0, 3);
assertArrayEquals(firstThree.toArray(), sList.toArray());
}
@Test
public void givenStudentScores_whenNameMatches_thenFindFirstStudent() {
String matchString = "3";
Student student = studentRepo.findFirstByNameLike("%" + matchString + "%", Sort.by("score")
.descending());
Student s = students.stream()
.filter(a -> a.getName()
.contains(matchString))
.findFirst()
.orElse(null);
assertEquals(student, s);
}
@Test
public void givenStudentScores_whenBetweenRange_thenFindFirstTwoStudents() {
List<Student> topTwoBetweenRange = studentRepo.findFirst2ByScoreBetween(50, 60, Sort.by("score")
.descending());
List<Student> _students = students.stream()
.filter(a -> a.getScore() >= 50 && a.getScore() <= 60)
.limit(2)
.collect(Collectors.toList());
assertArrayEquals(_students.toArray(), topTwoBetweenRange.toArray());
}
}