I've searched here on SO and the web but couldn't find an answer to this problem. How do I write the following MySQL query using JPQL or JPA's Criteria API?
public String getLanguage(String language) {
String query = "SELECT i18n." + language + " AS translated FROM i18n";
}
I realise this specific query is meaningless, but the problem for me is to choose column dynamically. Ie select i18n.language where 'language' is chosen at run time.
I could imagine it to look something like:
public List getLanguage(String language) {
return entityManager.createQuery(
"SELECT l.:language FROM I18n i"
).getResultList();
}
but this doesn't compile. Thanks
You can't do it with parameter, since the parameter can't be used to replace column name, but you can do it in a way similar to what you do in plain SQL
public List getLanguage(String language) {
return entityManager.createQuery("SELECT i." + language + " as translated FROM I18n i").getResultList();
}
EDIT
One way to do it with parameter, but it's not really dynamical solution, you would have to hard code all the options
SELECT CASE WHEN :language = 'EN' THEN i.en WHEN :language = 'MK' THEN i.mk END as translated FROM I18n i"
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.