0

I am using

session.getNamedQuery("query1").setString("a", "123") 
session.getNamedQuery("query2").setString("b", "123") 
session.getNamedQuery("query3").setString("c", "123") 

to set parameter.

<sql-query name="query1">
    select * from table where a = :a
</sql-query>

<sql-query name="query2">
    select * from table where b = :b
</sql-query>

<sql-query name="query3">
    select * from table where c = :c
</sql-query>

How can I call any one of sqls using only one namedQuery for example

<sql-query name="query">
    select * from table where (it can be a or b or c ) = :(it can be a or b or c )
</sql-query>

This named query should be work both

session.getNamedQuery("query").setString("a", "123")

and

session.getNamedQuery("query").setString("c", "123")
maskapsiz
  • 244
  • 5
  • 23

2 Answers2

0

Try this out:

 <sql-query name="query-Once">
    <return alias="employee" class="com.kuntal.common.Employee"/>
    <![CDATA[select * from employee e where e.emp_fname = :empFname and e.emp_lname:empLname]]>
    </sql-query>

Now from your code use:

Query query = session.getNamedQuery("query-Once")
.setString("empFname", "Kuntal")
.setString("empLname","Ganguly");

basically you need to create a java pojo model object for your table with the attribute that you want to set.Then finally you can set those through one named query only as shown above.Hope its helps you !

Kuntal-G
  • 2,970
  • 16
  • 16
  • Can it work when only I set Query query = session.getNamedQuery("query-Once").setString("empFname", "Kuntal"); – maskapsiz Jul 17 '14 at 10:37
  • Yes @maskapsiz it will work! But then you have to change your sql query to <![CDATA[select * from employee e where e.emp_fname = :empFname OR e.emp_lname:empLname]]> . SQL query needs to be tuned from and to or. now you can either set empFname or empLname or even both. Because named or native query behind the back changes to sql query only.Let me know if you have any issue. – Kuntal-G Jul 17 '14 at 10:57
0

Java file

session.getNamedQuery("myquery").setString("a", "123").setString("b", "123").setString("c", "123");

hbm.xml entry

<sql-query name="myquery">
    <return alias="table" class="com.tutorial.Table"/>
    <![CDATA[select * from table t where t.a = :a or t.b=:b or t.c=:c]]>
</sql-query>
Ajinkya
  • 147
  • 1
  • 2
  • 11