JPA nativeQuery 变量为null,存在bytea不存在:或者upper(bytea)不存在问题

x33g5p2x  于2022-01-06 转载在 其他  
字(1.6k)|赞(0)|评价(0)|浏览(233)
@Query(
		value = "select * from products where "
			+ " case when :XXXXRegion is not null and :xxxxRegion!='' then upper(xxxx_region) =upper(:xxxxRegion) else 1=1 end "
			+ " and "
			+ " case when :xxxxModel is not null and :xxxxModel !='' then upper(xxxx_model) =upper(:xxxxModel) else 1=1 end "
			+ " and "
			+ " case when :systemPlatform is not null and :systemPlatform!='' then upper(system_platform) =upper(:systemPlatform) else 1=1 end "
			+ " ORDER BY id ASC, effective_time desc", nativeQuery = true
	)
	fun findByRegionAndFastoneModelAndSystemPlatform(
		@Param("fastoneRegion")
		fastoneRegion: String?,
		@Param("fastoneModel") xxxxModel: String?,
		@Param("systemPlatform") systemPlatform: SystemPlatform?
	): List<Product>

如果代码是这样写的话,如果存在xxxxModel 传递进来的是null 就会直接报错,jpa的nativeQuery对于null值处理不了

可以service加强对null值的处理

或者

使用QUERYDSL 来做查询

fun findVmByFastoneRegionAndSystemPlatformAndFastoneModelAndVendor(
		region: Region?,
		platform: SystemPlatform?,
		fastoneModel: String?,
		vendor: Vendor?
	): List<Product> {
		val product = QProduct.product
		val productTypeExpression = product.productType.eq(ProductType.VM)
		val regionExpression = region?.let { product.fastoneRegion.eq(region) }
		val fastoneModelExpression = fastoneModel?.let { product.fastoneModel.eq(fastoneModel) }
		val platformExpression = platform?.let { product.systemPlatform.eq(platform) }
		val vendorExpression = vendor?.let { product.vendor.eq(Vendor.AWS) }
		val buildExpression =
			productTypeExpression.and(regionExpression).and(fastoneModelExpression).and(platformExpression)
				.and(vendorExpression)
		return repository.findAll(buildExpression, product.id.asc(), product.effectiveTime.desc()).toList()
	}

避免因为null值造成程序出现错误

相关文章