IN converting over a legacy application we need to convert named query to nhibernate. The problem is that the where clause is being set.
here is the mapping
<resultset name="PersonSet">
<return alias="person" class="Person">
<return-property column="id" name="Id" />
<return-property column="ssn" name="Ssn" />
<return-property column="last_name" name="LastName" />
<return-property column="first_name" name="FirstName"/>
<return-property column="middle_name" name="MiddleName" />
</return>
</returnset>
<sql-query name="PersonQuery" resultset-ref="PersonSet" read-only="true" >
<![CDATA[
SELECT
person.ID as {person.Id},
person.SSN as {person.Ssn},
person.LAST_NAME as {person.LastName},
person.MIDDLE_NAME as {person.MiddleName},
person.FIRST_NAME as {person.FirstName},
FROM PERSONS as person
where :value
]]>
</sql-query>
and the c# code:
String query = "person.LAST_NAME = 'Johnson'";
HibernateTemplate.FindByNamedQueryAndNamedParam("PersonQuery", "value", query);
The error:
where ?]; ErrorCode []; An expression of non-boolean type specified in a context where a condition is expected, near ‘@p0’.
This doesn’t work because you try to replace
:valuewith"person.LAST_NAME = 'Johnson'"wanting that the query becomesThis won’t work. You can only replace the ‘Johnson’ part dynamically not the whole condition. Thus what really gets generated is
Which obviously isn’t a valid condition for the WHERE-part as there is only a literal but no column and operator to compare the field to.
If you only have to match against
person.LAST_NAMErewrite the xml-sql-query toAnd in the C# code set
If you need to dynamically filter by different columns or even multiple columns at a time use filters. e.g. like this (i made a few assumptions on you hibernate-mapping file)
Now in your code you should be able to do
If you need still more dynamic queries (e.g. even changing the operator (=, !=, like, >, <, …) or you have to combine restrictions logically (where lastname = “foo” OR firstname” = “foobar”) then it’s definitly time to look into the
Hibernate Criteria API