'Is there a way to return collection instead of entity in @Repository's @Query
I have a query:
@Query(
value = "select name, age, now() from received.scheme ;",
nativeQuery = true
)
public {???} selectData()
I cannot create or return an entity for such a scheme as there is no natural id in it, so is there a way to return something like List<Triple<String, Int, LocalDateTime>>?
Solution 1:[1]
you can create another class with the required properties which you want to retrieve from the database and then you can return that class as List<Class>.
Solution 2:[2]
In your code you get the data from: scheme
So the Entity SchemeEntity should contains those three fields:
- name
- age
- now (creationDate for example it depend on your logic)
Then your method should be like this:
@Query(value = "select name, age, now() from received.scheme ;",
nativeQuery = true
)
public List<SchemeEntity> selectData();
Solution 3:[3]
You can provide a PROJECTION entity which will have 3 attributes and must provide a parametrized constructor with those 3 attributes you want to fetch ,or you can still get them as a List<Object[]> and then hydrate your entity.
Solution 4:[4]
I've tried those things but what worked for me is using ctid as an @Id. Since I only needed some sort of a mock id, it worked fine.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | rg226965 |
| Solution 2 | Mohamed Aymen Charrada |
| Solution 3 | karim farhouti |
| Solution 4 | Jhanzaib Humayun |
