Skip to content

Instantly share code, notes, and snippets.

@jonilsonds9
Last active February 6, 2024 23:59
Show Gist options
  • Save jonilsonds9/12ae56d073fc3d9e67a030923b0328a1 to your computer and use it in GitHub Desktop.
Save jonilsonds9/12ae56d073fc3d9e67a030923b0328a1 to your computer and use it in GitHub Desktop.
Spring Data JPA Projection com List Nested Projection
// Temos primeiro as projections:
// CategoryProjection.java
public interface CategoryLoginProjection {
String getName();
String getCode();
String getIconPath();
List<SubcategoryLoginProjection> getSubcategories();
}
// SubcategoryProjection.java
public interface SubcategoryLoginProjection {
String getName();
}
// Agora temos o nosso repository com uma JPQL query para buscar e filtrar as categorias, subcategorias e cursos
// e usando nossas projections:
// CategoryRepository.java
public interface CategoryRepository extends JpaRepository<Category, Long> {
@Query(value = """
select distinct c from Category c
left join fetch c.subcategories s
left join s.courses x
where c.active = true and s.active = true and x.visible = true
""")
List<CategoryLoginProjection> findCategoriesProjection();
}
// Veja mais sobre fetch na query:
// https://stackoverflow.com/questions/5816417/how-to-properly-express-jpql-join-fetch-with-where-clause-as-jpa-2-criteriaq
@minhtran-q
Copy link

Does it work?

@jonilsonds9
Copy link
Author

Yes, it's working, but it may have unexpected behavior

@minhtran-q
Copy link

Thanks for your reply

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment