I have this function in my DB
CREATE FUNCTION BookBed (pPaciente varchar(255),
pHospital bigint(20)) RETURNS BOOLEAN
BEGIN
DECLARE NumLeitosDisponiveis INT;
DECLARE vReservaOK BOOLEAN;
DECLARE dt TIMESTAMP;
SET dt = (Select now());
SET NumLeitosDisponiveis = (SELECT AVAILABLEBEDCOUNT FROM HOSPITAL WHERE ID = pHospital);
IF((SELECT NumLeitosDisponiveis) > 0) THEN
BEGIN
START TRANSACTION;
INSERT INTO RESERVATION(PERSON, HOSPITAL, DATE) VALUES (pPaciente, pHospital, dt);
UPDATE HOSPITAL
SET AVAILABLEBEDCOUNT = AVAILABLEBEDCOUNT - 1
WHERE ID = pHospital;
SET vReservaOk = true;
commit;
END;
ELSE
SET vReservaOk = false;
END IF;
RETURN vReservaOK;
END;
In the if part of my if-else statement, I would like to perform all the operations in a atomic way.
I wanted to use the START TRANSACTION command, but they are disallowed in functions and I couldn’t find any other command to perform it.
Are functions atomic by default?
If not, is there any way I can implement it?
Thanks,
Oscar
EDIT: And if I have to use a function, is it possible to have transactions?
Use a stored procedure with an output parameter for returning the operation status.
If you are having trouble calling the stored procedure using Hibernate, then move the transaction logic to Hibernate. That is, start, commit or rollback the transaction using Hibernate constructs.
EDIT
Transactions require using the InnoDB engine as @bobobobo notes on the comments.