postgresql JSON查询语句like及其spring boot jpa的使用

x33g5p2x  于2022-04-20 转载在 Spring  
字(1.1k)|赞(0)|评价(0)|浏览(706)

在开发中经常遇到数据库存储的json数据,需要查询出来,比如:

select * from event  where resource_type='COMPUTE' and event_type='START' and deleted=FALSE  
      and resource_data ->>'eniIds' like   '%ocid1.vnic.oc1.ap-tokyo-1.abxhiljruybcqzennifrmchug63gyfpki4ano6ylo3hmse2atlkl2rjx635a%'

但是同样的代码放在spring boot JPA中就会报错。

@Query(
		value = "select * from event  where resource_type='COMPUTE' and event_type='START' and deleted=FALSE " +
			" and resource_data ->>'eniIds' like %'+:eniId+'%",
		nativeQuery = true
	)
	fun findUserIdAndTenantIdByEniId(@Param("eniId") eniId:String):List<Event>

正确的SQL写法:

select * from event  where resource_type='COMPUTE' and event_type='START' and deleted=FALSE  
      and resource_data ->>'eniIds' like concat('%','ocid1.vnic.oc1.ap-tokyo-1.abxhiljruybcqzennifrmchug63gyfpki4ano6ylo3hmse2atlkl2rjx635a','%')

正确的JAVA JPA写法:

@Query(
		value = "select * from event  where resource_type='COMPUTE' and event_type='START' and deleted=FALSE " +
			" and resource_data ->>'eniIds' like concat('%',:eniId,'%')",
		nativeQuery = true
	)
	fun findUserIdAndTenantIdByEniId(@Param("eniId") eniId:String):List<Event>

相关文章