MyBatis Mapper

전승원·2021년 1월 10일
0

@Mapper
public interface UserMapper {
@Insert("INSERT INTO USERS (username, salt, password, firstname, lastname) " +
"VALUES(#{username}, #{salt}, #{password}, #{firstName}, #{lastName})")
@Options(useGeneratedKeys = true, keyProperty = "userId")
int insert(User user);
}

Let's think about what the Insert query actually returns.

Unlike a Select Query, Usually it only returns a count of the number of rows as a result of statement. That's useful for a quickcheck that something was changed correctly.

But when we're inserting a record with an auto-generated id, we often wanna know what that generated id is.
For example, if we need to insert another record that has a foreign key relationship to the record we just inserted.

I am not 100% sure but example code of case above would be like this.

Integer justInsertedRecordId = userMapper.insert(user);
Coupon coupon = new Coupon();
User user = userMapper.findUserById(justInsertedRecordId);
coupon.setUser(user);
couponMapper.insert(coupon);
profile
No pleasure, No gain

0개의 댓글