I can not find an example of mapping in MyBatis that I can replace the below code with.
“if sqlcode <> 0” If no update takes place then do an insert
Any sugestions? 🙂
as
begin
execute SetDefaultIsolationLevel
update COMPANYLEVEL
set
companylevelid = @companylevelid,
companynameid = @companynameid,
level = @level,
memo = @memo,
operator = @operator,
changed = getdate(*)
where
companynameid = @companynameid
if sqlcode <> 0
BEGIN
insert into COMPANYLEVEL
(companylevelid,companynameid,level,memo,operator,changed)
values
(@companylevelid,@companynameid,@level,@memo,@operator,getdate(*))
END
commit transaction
end
I don’t think MyBatis has any mapping to say “try an update, if that fails do an insert”. If you want that done in one round trip to the database, then a stored procedure is appropriate. You can call this stored procedure from MyBatis, but the if/else logic would be in the stored proc.
If you are trying to get rid of the stored proc, then you’ll need a two step check in your code. An update in MyBatis returns the number of rows updated (via the JDBC driver), so if that is zero, then you can call a MyBatis insert mapping. In cases where an insert occurs, it would require two round trips to the database.
You could also do an “upsert” using a MERGE statement in a stored proc, but that of course isn’t related to MyBatis other than MyBatis can call your stored proc. It looks like you are using Sybase? If so, I’m not sure if Sybase has upserts – link to research: Upsert (update or insert) in Sybase ASE?