Skip to content

Instantly share code, notes, and snippets.

@arseto
Last active October 1, 2022 07:45
Show Gist options
  • Save arseto/f214e50917878dc31aec2ebb5af92d2e to your computer and use it in GitHub Desktop.
Save arseto/f214e50917878dc31aec2ebb5af92d2e to your computer and use it in GitHub Desktop.
JPA Native Query with Kotlin and Spring
@Service
class SalesOrderServiceImpl @Autowired constructor (
val em: EntityManager
) : SalesOrderService {
override fun getDailySalesData(reportFilter: ReportFilter)
: List<SalesData> {
val q = em.createNativeQuery("""
SELECT
s.date,
sum(sd.price) as amount
FROM sales s
left join sales_details sd
on s.id = sd.sales_id
where
s.date between ?1 and ?2
group by s.date
""")
.setParameter(1, reportFilter.getStartDateTimestamp())
.setParameter(2, reportFilter.getEndDateTimestamp())
val resultList = q.getResultList().toList()
val result = resultList.map {
it ->
val lst = it as Array<out Any>
SalesData(
lst[0] as? BigInteger,
lst[1] as? BigDecimal
)
}
return result
}
}
@ptit-toantran
Copy link

Thanks, this also save my life :)

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