1
<sql-query name="sql">
   select :COLUMN_NAME from table.
</sql-query>

I want to set COLUMN_NAME using

this.sessionFactory.getCurrentSession().getNamedQuery("sql")
                .setString("COLUMN_NAME", "id");

I got a wrong result when I use this code (I know where I fail). Is there any way to set COLUMN_NAME using getNamedQuery() and setString().

Amin Abu-Taleb
  • 4,423
  • 6
  • 33
  • 50
maskapsiz
  • 244
  • 5
  • 23

2 Answers2

0

Have you tried setParameter method?

this.sessionFactory.getCurrentSession().getNamedQuery("sql")
                .setParameter("COLUMN_NAME", "id");

Further info

Amin Abu-Taleb
  • 4,423
  • 6
  • 33
  • 50
  • No it doesn't work. it seems COLUMN_NAME as String like select "COLUMN_NAME" from table so it returns COLUMN_NAME word. – maskapsiz Mar 04 '14 at 15:21
  • So you want to change the name of the column dynamically, why? – Amin Abu-Taleb Mar 04 '14 at 15:25
  • Because table has columns like col1 col2 col3 ... col100. I only want to use 3 columns but these 3 colums can be col5 col10 col30 or col7 col8 col9 or any other option so I want to change sql column name dynamically and call sql like "select col1, col5, col99 from table" – maskapsiz Mar 04 '14 at 15:33
0

You must add <return-scalar column="name_first" type="string" /> to get specific column. like

    <sql-query name="sql">
       <return-scalar column="COLUMN_NAME" type="java.lang.String" />
       select :COLUMN_NAME from table.
    </sql-query>

Or you can use setResultTransformer method if you had created a bean class for that table.

Vishrant
  • 15,456
  • 11
  • 71
  • 120
  • it return org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions ERROR: Invalid column name but column name is true – maskapsiz Mar 04 '14 at 15:54
  • You will have to map your table column in your `.hbm` file or through `annotations` – Vishrant Mar 05 '14 at 09:48
  • After reading your other comment `I only want to use 3 columns but these 3...` I have a question, will the Data Type of these column will be same, or it will change like sometime it will be `Integer` sometime `Date` or something. – Vishrant Mar 05 '14 at 09:52