In this Spring Data JPA article, I’d like to share some code examples which you can use to sort a list of entities by a nested property. It’s very common of having the following entity relationship among Product, Category and Brand:

product class diagram

Here, a Product entity has references to Category and Brand entities. And it’s very natural that the end users want to sort a list of products by brand name, for example:

Sort by brand name

Or sort the products list by category name:

Sort by category name

In this case, we need to sort a collection of Product entities by nested property, e.g. product.brand.name and product.category.name. Let’s see how to implement this kind of sorting with Spring Data JPA. Suppose that we have code of the Product entity class as follows:

package net.codejava;

@Entity
@Table(name = "products")
public class Product {

	@Column(length = 256, unique = true, nullable = false)
	private String name;
	
	@ManyToOne
	@JoinColumn(name = "brand_id")
	private Brand brand;
	
	@ManyToOne
	@JoinColumn(name = "category_id")
	private Category category;

	@Transient
	public String getShortName() {
		if (name.length() > 40) {
			return name.substring(0, 40).concat("...");
		}
		return name;
	}

	// other fields, getters and setters...	
}
Code of the Brand class:

package net.codejava;

@Entity
@Table(name = "brands")
public class Brand {
	
	@Column(length = 45, nullable = false, unique = true)
	private String name;

	// other fields, getters and setters...	
	
}
Code of the Category class:

package net.codejava;

@Entity
@Table(name = "categories")
public class Category {

	@Column(length = 128, nullable = false, unique = true)
	private String name;

	// other fields, getters and setters...	
}


With Spring Data JPA, we need to declare the repository interface for product as follows:

package net.codejava;

public interface ProductRepository extends PagingAndSortingRepository<Product, Integer> {

}
And to tell Spring Data JPA to sort a collection of Product entities by brand name, you need to create a Sort object like this:

Sort sort = Sort.by("brand_name").ascending();
Spring Data JPA will understand the field name “brand_name” as nested property, i.e. the field name of the Brand object referred to by a Product object. For your reference, below is code example of a Spring Data JPA unit test class that tests sorting products by brand name in ascending order:

package net.codejava;

@DataJpaTest
@AutoConfigureTestDatabase(replace = Replace.NONE)
@Rollback(false)
public class ProductRepositoryTests {

	@Autowired
	private ProductRepository repo;
	
	@Test
	public void testSortProductsByBrandName() {
		Sort sort = Sort.by("brand_name").ascending();
		Pageable pageable = PageRequest.of(0, 30, sort);
		Iterable<Product> products = repo.findAll(pageable);
		
		products.forEach(p -> {
			System.out.printf("%-50s - %s\n", p.getShortName(), p.getBrand().getName());
		});
	}
	
}
This would produce the following output (sample data):

Sort products by brand name

Similarly, below is another code example - a unit test for listing products by category name in descending order:

@Test
public void testSortProductsByCategoryName() {
	Sort sort = Sort.by("category_name").descending();
	Pageable pageable = PageRequest.of(0, 30, sort);
	Iterable<Product> products = repo.findAll(pageable);
	
	products.forEach(p -> {
		System.out.printf("%-50s - %s\n", p.getShortName(), p.getCategory().getName());
	});
}
And sample output:

sort products by category name

And when implementing sorting functionality in the view layer with Thymeleaf, make sure to specify the field name for nested property like this:

http://localhost/.../products/page/1?sortField=category_name&sortDir=asc

http://localhost/.../products/page/1?sortField=brand_name&sortDir=desc

That’s my tip about sorting by nested property with Spring Data JPA. I hope you found the code examples helpful.

Watch the following video to see the coding in action:

 

Related Spring Data JPA Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.



Add comment