简体   繁体   中英

Unable to execute a SP via a namedQuery declared in *.hbm.xml file

I'm trying out a POC to use namedQueries in Hibernate on MS SQL Server 2012 and have configured the following in my Reminder.hbm.xml configuration.

<hibernate-mapping>
    <class name="com.reminder.hibernate.model.Reminder" table="Reminders">
    ...
    ...
    </class>

    <sql-query name="fetchDOBsBasedOnDate">
        <return alias="reminder" class="com.reminder.hibernate.model.Reminder"/>
        <![CDATA[EXEC FetchDOBsBasedOnDate(:birthDate)]]>
    </sql-query>

</hibernate-mapping>

and I'm trying to call the above named query from a Java class as like this:

Query query = session.getNamedQuery("fetchDOBsBasedOnDate").setDate("birthDate", new Date(new java.util.Date().getTime()));
//Used java.sql.Date above

Following is the single SQL statement that I've put in a stored procedure as I was unable to run the query itself, here is the code for the stored procedure.

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE FetchDOBsBasedOnDate 
@InputDate DATETIME
AS
BEGIN
    SET NOCOUNT ON;
    SELECT * FROM Reminders WHERE DATEADD(year, DATEDIFF(year, BirthDate, @InputDate), BirthDate) = @InputDate
END
GO

Problem is that, I'm getting an error executing this SP through Hibernate where as the SP works altogether. Error that I see on my console:

Hibernate: EXEC FetchDOBsBasedOnDate(?)
1 Apr, 2016 3:48:14 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 102, SQLState: S0001
1 Apr, 2016 3:48:14 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Incorrect syntax near '@P0'.

EDIT: After getting rid of the paranthesis, SQL syntax errors are suppressed but I'm still not getting the results.

You don't want parentheses around your stored procedure parameter list . Try:

<![CDATA[EXEC FetchDOBsBasedOnDate :birthDate]]>

Don't forget you can always try your SQL out from a standalone client like SQL Server Management Studio to see if it's valid.

Also, you seem to be using a date with a time component (I don't know much about the classes you're using, but if that's java.util.Date, it stores time as well, with millisecond precision.) Can you print the parameter value from your Java code to see exactly what you're querying, or turn on any kind of query logging? I have a feeling you may be looking for people whose birthdays are at an exact millisecond point in time during the day, which presumably won't be found in your database.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM