1

How to write a Hibernate query to select values with more then two values?

metrics = new long[]{1, 2, 3};
rprtAutoCustomColum = reportSettingServive.getColumnsMap("1,2,3");

There are three columnId's. I want to select the columnId and variable name and store in a HashMap

public Map<Long, String> customeCol = new HashMap<>();

public HashMap<Long, String> getColumnsMap(String columnIds) {
    Session session = null;
    Transaction transaction = null;
    List<ReportsAutomationCustomColumns> automationCustomColumns = new ArrayList();

    SQLQuery query;
    try {
        session = sessionFactory.openSession();
        transaction = (Transaction) session.beginTransaction();
        String hql = "from lxr_reportsauto_customcolumns  where column_id=:columnIds";
        Query query = session.createQuery(hql);
        List<ReportsAutomationCustomColumns> list = query.list();
        transaction.commit();

        list.stream().forEach((ReportsAutomationCustomColumns clist) -> {
            customeCol.put(clist.getColumnId(), clist.getVariableName());
        });
        return (HashMap<Long, String>) customeCol;
    }
}

Normal SQL looks like:

select column_id,variable_name from lxr_reportsauto_customcolumns
where column_id in(1,2,3) order by column_id 

But I want in Hibernate.

1 Answer 1

1

You need to create a List with the values you want and then pass it to your query, like this:

List<Long> values = new ArrayList<Long>();
values.add(1L);
values.add(2L);
values.add(3L);

String hql = "from lxr_reportsauto_customcolumns  where column_id in (:columnIds)";
Query query = session.createQuery(hql);
query.setParameterList("columnIds", values);
Sign up to request clarification or add additional context in comments.

2 Comments

Hi Hugo, When i tried to run above code its throwing the following exp. ex = (org.hibernate.hql.internal.ast.QuerySyntaxException) org.hibernate.hql.internal.ast.QuerySyntaxException: lxr_reportsauto_customcolumns is not mapped [from lxr_reportsauto_customcolumns where column_id in (:columnIds)]
In HQL, insted of using the table name, you must use the class name that's mapped to that table. (so instead of "lxr_reportsauto_customcolumns", use the class name mapped to it)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.