'Populating a non-column field in entity using Spring Repository
I want to use a native query from database to retrieve more data for a given record, and I'm looking for a solution on how to declare the fields that accommodate this data.
If I do not annotate the field, during updates JPA thinks this field should be mapped to a column with the same name (which of course doesn't exist in the table); if I annotate it with @Transient, the field is ignored on update, but also ignored on select (why?).
Let's clarify with an example. I have the entity Discount
class Discount {
@Column(name = "ID")
private long id;
@Column(name = "PRODUCT_ID")
private long productId;
// private String productName; <-- Uncommented, error on save; with @Transient empty on read
}
And when I retrieve a discount from database, I also want to use the same query to return the whole record plus the name of the product which comes from Product table.
Using Spring repositories I set up the query as follow:
public interface DiscountRepo extends Repository<Discount, Long> {
@Query(nativeQuery = true, value = "select d.*,p.name as productName from discount d join product p on d.product_id = d.id")
List<Discount> getAll();
}
The reason I don't want to have a property like private Product product in the Discount entity, is that on select too much data would be transferred from database, while I only need the product name.
Solution 1:[1]
You can use JdbcTempate and then map return value to Discount.class
String sqlQuery = "select d.ID as id , d.PRODUCT_ID as productId p.name as productName from discount d join product p on d.product_id = d.id";Map<String, Object> result = jdbcTemplate.queryForMap(sqlQuery);Discount discount = new ObjectMapper().convertValue(result, Discount.class);
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 | Muhammad Awais Rashid |
