简体   繁体   English

如何通过Java和Hibernate的特定列对MySQL查询进行排序?

[英]How to order by a specific column a MySQL query with Java and Hibernate?

I'm trying to use the same query to sort my table columns but when I pass as a parameter the column to ORDER BY, it adds quotes before and after my column name. 我正在尝试使用相同的查询对表列进行排序,但是当我将该列作为参数传递给ORDER BY时,它会在列名的前后添加引号。 If you are using ORDER BY parameter, the column name have to be written without being between quotes or MySQL is going to ignore it. 如果您使用ORDER BY参数,则必须写出列名,而不能在引号之间,否则MySQL将忽略它。

Example or query to execute: 要执行的示例或查询:

select * from app_user ORDER BY mobile_token ASC LIMIT 0 , 20

This is what hibernate send to MySQL: 这就是休眠发送到MySQL的内容:

select * from app_user ORDER BY 'mobile_token' ASC LIMIT 0 , 20

Java query: Java查询:

query = JPA.em().createNativeQuery("select * from app_user ORDER BY :column ASC LIMIT :init , :page",AppUser.class);
query.setParameter("column", column);
query.setParameter("init", pageNumber*pageSize);
query.setParameter("page", pageSize);

I could change the NativeQuery by: 我可以通过以下方式更改NativeQuery:

"select * from app_user ORDER BY "+column+" ASC LIMIT :init , :page"

but this is going to become my app unsafety. 但这将成为我的应用程序的不安全因素。

You can only pass values as parameters to a query. 您只能将值作为参数传递给查询。 Not column or field names. 不是列名或字段名。 That would make it impossible for the database to know which columns are actually used in the query, and thus make it impossible to prepare the execution plan. 这将使数据库无法知道查询中实际使用了哪些列,从而无法准备执行计划。

So your solution using concatenation is the only one. 因此,使用串联的解决方案是唯一的解决方案。 Just make sure the column doesn't come from the user. 只要确保该列不是来自用户即可。 Or if it comes from the user, that it's a valid column name and that the user is allowed to use it. 或者,如果它来自用户,则它是有效的列名,并且允许用户使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM