mybatis调用mysql存储过程 mysql
程序员文章站
2022-05-29 13:26:19
...
mybatis调用mysql存储过程
1.mybastis的配置
<select id="grabRedPacketProcedure">
call grabRedPacketProcedure(?,?,?)
</select><parametermap type="java.util.Map" id="paramMap"><parameter property="redPacketId" mode="IN" javatype="INTEGER"></parameter><parameter property="userId" mode="IN" javatype="INTEGER"></parameter><parameter property="num" mode="OUT" javatype="INTEGER" jdbctype="INTEGER"></parameter></parametermap>
2.mapper
@Mapper
public interface RedPacketMapper {
public int insertRedPacketUser(RedPacketUserPO po);
//调用存储过程
public void grabRedPacketProcedure(Map<string integer> map);
}
3.mysql存储过程
delimiter //
DROP PROCEDURE IF EXISTS grabRedPacketProcedure
//
create PROCEDURE grabRedPacketProcedure(IN v_red_packet_id INTEGER,IN v_user_id INTEGER,OUT num INTEGER)
begin
set num:= -1;
select @total:=stock from red_packet where id = v_red_packet_id;
if @total &gt; 0 then
begin
start transaction;
update red_packet set stock=stock-1 where id = v_red_packet_id;
insert into red_packet_user(red_packet_id,user_id,amount) values (v_red_packet_id,v_user_id,5);
commit;
set num:= 1;
end;
end if;
end
//
DELIMITER ;
4.存储过程的调用
public int grapRedPacketProc(Integer redPacketId, Integer userId) {
int num = -1;
Map<string> map = new HashMap<string integer>();
redPacketMapper.grabRedPacketProcedure(map);
if(map.containsKey("num")) {
num = map.get("num");
}
return num;
}
</string></string></string>
1.mybastis的配置
<select id="grabRedPacketProcedure">
call grabRedPacketProcedure(?,?,?)
</select><parametermap type="java.util.Map" id="paramMap"><parameter property="redPacketId" mode="IN" javatype="INTEGER"></parameter><parameter property="userId" mode="IN" javatype="INTEGER"></parameter><parameter property="num" mode="OUT" javatype="INTEGER" jdbctype="INTEGER"></parameter></parametermap>
2.mapper
@Mapper
public interface RedPacketMapper {
public int insertRedPacketUser(RedPacketUserPO po);
//调用存储过程
public void grabRedPacketProcedure(Map<string integer> map);
}
3.mysql存储过程
delimiter //
DROP PROCEDURE IF EXISTS grabRedPacketProcedure
//
create PROCEDURE grabRedPacketProcedure(IN v_red_packet_id INTEGER,IN v_user_id INTEGER,OUT num INTEGER)
begin
set num:= -1;
select @total:=stock from red_packet where id = v_red_packet_id;
if @total &gt; 0 then
begin
start transaction;
update red_packet set stock=stock-1 where id = v_red_packet_id;
insert into red_packet_user(red_packet_id,user_id,amount) values (v_red_packet_id,v_user_id,5);
commit;
set num:= 1;
end;
end if;
end
//
DELIMITER ;
4.存储过程的调用
public int grapRedPacketProc(Integer redPacketId, Integer userId) {
int num = -1;
Map<string> map = new HashMap<string integer>();
redPacketMapper.grabRedPacketProcedure(map);
if(map.containsKey("num")) {
num = map.get("num");
}
return num;
}
</string></string></string>