1、创建数据库表account,该表包含username和balance,分别表示账户名和账户余额,具体见上篇博客。
2、建立dao包,com.example.demo.dao
在dao包下面创建AccountDao接口
package com.example.demo.dao;
@Mapper
public interface AccountDao {
@Update("update account set balance =balance + #{m} where username = #{username}")
public void updateAccountIn(@Param("username") String username,@Param("m") double m);
@Update("update account set balance =balance - #{m} where username = #{username}")
public void updateAccountOut(@Param("username") String username, @Param("m") double m);
}
接口中有两个方法updateAccountIn,updateAccountOut。一个用于增加账号的balance,一个用于减少账号的balance
3、建立service包,比如com.example.demo.service
在service下面创建接口AccountService和其实现类AccountServiceImp。
package com.example.demo.service;
public interface AccountService {
void transfer(int id);
}
package com.example.demo.service;
import com.example.demo.dao.AccountDao;
@Service
public class AccountServiceImp implements AccountService {
@Autowired
AccountDao ud;//注入Mybatis实现的dao
@Override
@Transactional//实现事务
public void transfer(int id) {
ud.updateAccountIn("zhangsan",200);
int i=1/0;
ud.updateAccountOut("lisi",200);
}
}
4.编写测试
自己编写