如何解决期待 IDENT,找到“:”
我正在为我的 Spring 项目构建本机查询。任何人都知道问题是什么?
@Query(value = "SELECT e.first_name as firstName,e.last_name as lastName,jh.start_date as startDate,jh.end_date as endDate," +
"j.job_title as jobName,d.department_name as departmentName FROM JOB_HISTORY jh " +
"JOIN JOBS j ON jh.JOB_ID = j.JOB_ID " +
"JOIN DEPARTMENTS d ON JH.DEPARTMENT_ID = d.DEPARTMENT_ID " +
"JOIN EMPLOYEES e ON jh.EMPLOYEE_ID = e.EMPLOYEE_ID " +
"ORDER BY jh.:sortBy :orderBy")
List<EmployeeJobView> getAllEmployeeJob(String sortBy,String orderBy);
org.hibernate.hql.internal.ast.QuerySyntaxException:期待 IDENT, 在第 1 行第 348 列附近找到“:” [SELECT e.first_name 作为 firstName, e.last_name 作为 lastName,jh.start_date 作为 startDate,jh.end_date 作为 endDate,j.job_title 作为 jobName,d.department_name 作为部门名称 从 JOB_HISTORY jh JOIN JOBS j ON jh.JOB_ID = j.JOB_ID JOIN DEPARTMENTS d ON JH.DEPARTMENT_ID = d.DEPAR TMENT_ID JOIN EMPLOYEES e ON jh.EMPLOYEE_ID = e.EMPLOYEE_ID ORDER BY jh.:sortBy :orderBy]
解决方法
如果我猜对了,我会使用 SPeL 重写最后一行:
def update(self,request,pk,**kwargs):
"""
Update Instance
"""
try:
partial = kwargs.pop('partial',False)
instance = self.get_custom_queryset(request).filter(id=pk)
core_user = User.objects.using(request.user.db).filter(email=request.user.email).first()
serializer = self.write_serializer_class(
data=request.data,partial=partial,context={"db": request.user.db,"core_user": core_user},)
if serializer.is_valid():
# extract many to many data
tags = serializer.validated_data.pop('tags',None)
attachments = serializer.validated_data.pop('attachments',None)
# update values
instance.update(**serializer.validated_data)
instance.first().save()
if getattr(instance,'_prefetched_objects_cache',None):
# If 'prefetch_related' has been applied to a queryset,we need to
# forcibly invalidate the prefetch cache on the instance.
instance._prefetched_objects_cache = {}
# save many2many data
if tags:
# delete all current tags to avoid duplications
instance.first().tags.set([])
# iterate and add
for tag_id in tags:
tag = Tag.objects.using(request.user.db).filter(pk=tag_id).first()
instance.first().tags.add(tag)
if attachments:
# delete all current legal_files to avoid duplications
instance.first().attachments.set([])
# iterate and add
for attachment_id in attachments:
attachment = base_models.Attachment.objects.using(request.user.db).filter(
pk=attachment_id).first()
instance.first().attachments.add(attachment)
instance.first().save(using=request.user.db,update_fields=['created'])
return Response(self.read_serializer_class(instance[0],many=False).data)
else:
# No correct data passed (TODO: Register log?)
return Response(
serializer.errors,status=status.HTTP_406_NOT_ACCEPTABLE)
except Exception as e:
# TODO: Unknown error,must be logged
return Response(
str(e),status=status.HTTP_500_INTERNAL_SERVER_ERROR)
正如 Simon Martinelli 所提到的,您应该使用 "ORDER BY jh.?#{[0]} ?#{[1]}"
。
另请参阅此处的 SPeL 和 JPA 指南https://spring.io/blog/2014/07/15/spel-support-in-spring-data-jpa-query-definitions。