I am using the following PostgreSQL function to delete a record from a table in the DB.
CREATE OR REPLACE FUNCTION deletesegment(segid bigint) RETURNS integer AS
$BODY$
DECLARE
rowsAffected integer := 0;
BEGIN
DELETE FROM segment
WHERE
id = segid;
GET DIAGNOSTICS rowsAffected = ROW_COUNT;
RETURN rowsAffected;
EXCEPTION
WHEN foreign_key_violation THEN
RAISE EXCEPTION foreign_key_violation;
END;
$BODY$
LANGUAGE plpgsql;
The primary key column of the above table (i.e. id column of segment table) is referenced as a foreign key by another table and when I execute the above function to delete a record from the segment table which is referenced by the other table, the function raises the error as expected (shown below).
ERROR: foreign_key_violation
********** Error **********
ERROR: foreign_key_violation
SQL state: 23503
Now I am calling this PostgreSQL function from my Java code which is using Hibernate as below,
public int deleteSegment(Long segmentId) {
SQLQuery query = (SQLQuery)sessionFactory.getCurrentSession().createSQLQuery("SELECT deletesegment(:segmentId)")
.setParameter("segmentId", segmentId);
int rows = (Integer)(query.list().get(0));
return rows;
}
When I pass in the same id to the above function (Integer)(query.list().get(0)) executes without raising any exceptions and returns 0. I expect it to throw an exception given that the underlying PostgreSQL function is raising an exception. But it doesn't.
What am I doing wrong. How can I make the exception to be raised in the Java code?
Thanks in advance..!!