Kastriot Beha
Kastriot Beha

Reputation: 9

How to return Map<String, Object> in Java, JPA?

I have two objects, Student and Book. Student has @OneToMany relationship with Book, and Book has only id, name, and publishYear. What i want is to return from Query is this:

select s.name, 
       b.name, 
       b.publishYear 
from Student s 
     inner join Book b on s.id = b.studentId

How to return s.name, b.name and b.publishYear with map, so i don't want to return a List but a map. How to do that?

Upvotes: 0

Views: 236

Answers (1)

Rando Shtishi
Rando Shtishi

Reputation: 1482

I am assuming you have a method findAll() which returns a list of with StudentBook objects that have properties student name, book name and book publish year.

Now to convert this method to return a map that has as key the book name and as values are book name and book published year to follow the code below:

        Map<String, Book> map = studentBookList.stream()
         .collect(Collectors.toMap(
                        StudentBook::getSname(), 
                        new Book(StudentBook::getBname(),
                                StudentBook::getPublishYear()
                                )
                        )
                );

Upvotes: 1

Related Questions