41
loading...
This website collects cookies to deliver better user experience
book_demo
database) according to the number of books they have published. Let's say that a top author is an author with more than 12 published books. We have to show a grid with the name of the top author and the number of books published.@Repository
public interface BookRepository extends JpaRepository<Book, Integer> {
interface TopAuthor{
String getAuthor();
int getBookCount();
}
...
@Query(value = "select author, count(id) as bookCount from book group by author having count(id) > ?1", nativeQuery = true)
List<TopAuthor> findTopAuthors(int bookCount);
}
nativeQuery = true
in the @Query
annotation. Spring Data will create objects of type TopAuthor
to build the result List
.@Service
public class BookService {
private final BookRepository repository;
...
public List<BookRepository.TopAuthor> findTopAuthors(int bookCount) {
return repository.findTopAuthors(bookCount);
}
}
@Route("report")
public class ReportView extends VerticalLayout {
public ReportView(BookService service) {
var grid = new Grid<>(BookRepository.TopAuthor.class);
grid.setSizeFull();
grid.setItems(service.findTopAuthors(12));
add(grid);
setSizeFull();
}
}
Grid
component is populated with the top authors returned by the service class.main
method in the Application
class and see the result in the browser. Depending on the number of books that your database has, the view is going to be rendered quickly or dramatically slowly! In my case, I added one million books to the database (I wrote an article that shows you how to generate many books for your database). With one million books, the view takes several seconds to appear in the browser as you can see in the video.author
column. This works in this over-simplistic example, but in a real-life project, you could easily have hundreds of tables with dozens of columns each. Dealing with indexes becomes kind of difficult, to say the least. MariaDB's ColumnStore allows us, among other things, to gain the advantages of indexes without having to manually configure indexes.CREATE TABLE book_analytics
(
id int(11) NOT NULL,
author varchar(255) DEFAULT NULL,
pages int(11) DEFAULT NULL,
publish_date date DEFAULT NULL,
title varchar(255) DEFAULT NULL
) engine=ColumnStore;
image_data
column from the original book
table since it makes little sense to have it in a table used for analytical purposes. Notice that we cannot add indexes to tables that use the ColumnStore engine. We don't have to. That's one of the advantages.insert into book_analytics(id, author, pages, publish_date, title)
select id, author, pages, publish_date, title from book;
book_analytics
table in the query we added to the repository:@Query(value = "select author, count(id) as bookCount from book_analytics group by author having count(id) > ?1", nativeQuery = true)
List<TopAuthor> findTopAuthors(int bookCount);