springboot+mybatis写一个交易
时间: 2023-12-31 12:16:31 浏览: 85
springboot+mybatis二手交易系统
5星 · 资源好评率100%
好的,下面是一个简单的 springboot + mybatis 实现交易的示例:
首先,我们需要定义交易实体类:
```java
public class Transaction {
private Long id;
private Long userId;
private BigDecimal amount;
// ... 省略其它属性、getter和setter方法
}
```
然后,我们需要定义一个 DAO 接口和对应的 mapper.xml 文件来实现交易的增删改查操作:
```java
public interface TransactionDao {
int save(Transaction transaction);
int delete(Long id);
int update(Transaction transaction);
Transaction getById(Long id);
List<Transaction> getByUserId(Long userId);
}
```
```xml
<!-- TransactionMapper.xml -->
<mapper namespace="com.example.dao.TransactionDao">
<insert id="save" parameterType="com.example.entity.Transaction">
insert into transaction(user_id, amount) values(#{userId}, #{amount})
</insert>
<delete id="delete" parameterType="Long">
delete from transaction where id = #{id}
</delete>
<update id="update" parameterType="com.example.entity.Transaction">
update transaction set user_id = #{userId}, amount = #{amount} where id = #{id}
</update>
<select id="getById" parameterType="Long" resultType="com.example.entity.Transaction">
select * from transaction where id = #{id}
</select>
<select id="getByUserId" parameterType="Long" resultType="com.example.entity.Transaction">
select * from transaction where user_id = #{userId}
</select>
</mapper>
```
接下来,我们需要编写一个 Service 层来封装 DAO 层的操作,并实现交易的业务逻辑:
```java
@Service
public class TransactionService {
@Autowired
private TransactionDao transactionDao;
@Transactional
public void transfer(Long sourceUserId, Long targetUserId, BigDecimal amount) {
// 扣除源用户的金额
Transaction sourceTransaction = new Transaction();
sourceTransaction.setUserId(sourceUserId);
sourceTransaction.setAmount(amount.negate()); // 注意这里需要取负值
transactionDao.save(sourceTransaction);
// 增加目标用户的金额
Transaction targetTransaction = new Transaction();
targetTransaction.setUserId(targetUserId);
targetTransaction.setAmount(amount);
transactionDao.save(targetTransaction);
}
}
```
最后,我们需要编写一个 Controller 层来处理 HTTP 请求:
```java
@RestController
@RequestMapping("/transactions")
public class TransactionController {
@Autowired
private TransactionService transactionService;
@PostMapping
public void transfer(@RequestParam("sourceUserId") Long sourceUserId,
@RequestParam("targetUserId") Long targetUserId,
@RequestParam("amount") BigDecimal amount) {
transactionService.transfer(sourceUserId, targetUserId, amount);
}
}
```
这样,我们就完成了一个简单的交易系统。当用户 A 要向用户 B 转账时,通过访问 `/transactions` 接口,将源用户的金额扣除,并将目标用户的金额增加。
阅读全文