简体   繁体   中英

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. 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.

Example or query to execute:

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

This is what hibernate send to MySQL:

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

Java query:

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:

"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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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