我在编写存储过程以插入父记录和'n'个子记录时遇到一些困难。我使用MySQL和Java和Spring NamedParameterJdbcTemplate。我的数据库表是:
contact:
id
firstName
lastName
....
contact_phone:
id
contactId
number
....
你可以看到这种关系是一对多的。我正在尝试编写一个存储过程,我可以传递联系信息和电话对象的ArrayList。我需要存储一些与电话号码相关的元数据。我想在存储过程中执行此操作,以便在其中一个插入因某些原因失败时回滚事务。
以下是我想要做的简化示例:
START TRANSACTION;
INSERT INTO contact(`lastName`,`firstName`,`primaryEmail`,`organizationId`) VALUE ('New Last','New First','New email',3);
SELECT LAST_INSERT_ID() INTO @newContactId;
INSERT INTO contact_phone(`contactId`,`number`,`organizationId`) VALUE (@newContactId,'+18011234567',3);
INSERT INTO contact_phone(`contactId`,`number`,`organizationId`) VALUE (@newContactId,'+18017654321',3);
INSERT INTO contact_phone(`contactId`,`number`,`organizationId`) VALUE (@newContactId,'+18019876543',3);
COMMIT;
这是我的存储过程的开始。我只是不确定如何传入一组电话对象,循环播放它们,并插入新记录。
DELIMITER $$
CREATE PROCEDURE `insert_contact`(
IN lastName VARCHAR(128),
IN firstName VARCHAR(128),
IN primaryEmail VARCHAR(320),
IN image_pointer VARCHAR(256),
IN locationId BIGINT(20),
IN organizationId BIGINT(20),
IN facebookPSID VARCHAR(256),
IN note TEXT,
IN locationNote VARCHAR(128),
IN inactiveDate BIGINT(20),
IN ??? How do I pass in an ArrayList of objects for my phones?)
BEGIN
DECLARE `_rollback` BOOL DEFAULT 0;
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET `_rollback` = 1;
START TRANSACTION;
INSERT INTO
contact(`lastName`, `firstName`, `primaryEmail`, `image_pointer`, `locationId`, `organizationId`, `facebookPSID`, `note`, `locationNote`, `inactiveDate`)
VALUES
(lastName, firstName, primaryEmail, image_pointer, locationId, organizationId, FacebookPSID, note, locationNote, inactiveDate);
SELECT LAST_INSERT_ID() INTO @newContactId;
-- *** Here is where I am stuck
-- Need to loop through list of these and insert them
-- INSERT INTO contact_phone(`contactId`, `number`, `city`, `state`, `country`, `zip`, `type`, `primary`, `smsCapable`, `organizationId`) VALUES (@newContactId, number, city, state, country, zip, type, primary, smsCapable, organizationId);
IF `_rollback` THEN
SET @RESULT=1;
ROLLBACK;
ELSE
SET @RESULT=0;
COMMIT;
END IF;
SELECT @RESULT;
END$$
DELIMITER ;