首先,你需要创建一个数据库表用于存储用户信息和账户余额。假设表名为user
,包含以下字段:id
、name
和balance
。
接下来,创建一个名为User
的实体类,与数据库表中的字段一一对应。
import com.baomidou.mybatisplus.annotation.TableName;
@TableName("user")
public class User {
private Long id;
private String name;
private BigDecimal balance;
// 省略getter和setter方法
}
然后,创建一个名为UserMapper
的Mapper接口,继承自MyBatis Plus提供的BaseMapper
接口。
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UserMapper extends BaseMapper<User> {
}
接下来,创建一个名为UserService
的服务类,用于处理转账逻辑。在该服务类中,注入UserMapper
并使用@Transactional
注解来标记事务。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
@Transactional
public void transfer(Long fromUserId, Long toUserId, BigDecimal amount) {
// 查询转出账户信息
User fromUser = userMapper.selectById(fromUserId);
// 查询转入账户信息
User toUser = userMapper.selectById(toUserId);
// 检查转出账户余额是否足够
if (fromUser.getBalance().compareTo(amount) < 0) {
throw new RuntimeException("Insufficient balance");
}
// 更新转出账户余额
fromUser.setBalance(fromUser.getBalance().subtract(amount));
userMapper.updateById(fromUser);
// 更新转入账户余额
toUser.setBalance(toUser.getBalance().add(amount));
userMapper.updateById(toUser);
}
}
最后,创建一个名为UserController
的控制器类,提供一个转账接口。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.math.BigDecimal;
@RestController
public class UserController {
@Autowired
private UserService userService;
@PostMapping("/transfer")
public String transfer(@RequestParam Long fromUserId, @RequestParam Long toUserId, @RequestParam BigDecimal amount) {
userService.transfer(fromUserId, toUserId, amount);
return "Transfer success";
}
}
以上就是一个简单的Spring Boot + MyBatis Plus事务转账案例。