每个人! 组态: 1.春季启动:Web,JPA,H2
应用程序:
@SpringBootApplication
public class BankApplication {
public static void main(String[] args) {
SpringApplication.run(BankApplication.class, args);
}
}
BankAccountDaoImpl:
@Repository
public class BankAccountDaoImpl implements BankAccountDao {
@Autowired
private EntityManagerFactory entityManagerFactory;
@Override
public void saveBankAccount(BankAccount bankAccount) {
Session currentSession = entityManagerFactory.unwrap(SessionFactory.class).openSession();
currentSession.save(bankAccount);
}
@Override
public BankAccount getBankAccount(int id) {
Session currentSession = entityManagerFactory.unwrap(SessionFactory.class).openSession();
BankAccount bankAccount = currentSession.get(BankAccount.class, id);
return bankAccount;
}
}
ClientAccountDaoImp:
@Repository
public class ClientAccountDaoImp implements ClientAccountDao{
@Autowired
private EntityManagerFactory entityManagerFactory;
@Override
public void saveClientAccount(ClientAccount clientAccount) {
Session currentSession = entityManagerFactory.unwrap(SessionFactory.class).openSession();
currentSession.saveOrUpdate(clientAccount);
}
@Override
public ClientAccount getClientAccount(int id) {
Session currentSession = entityManagerFactory.unwrap(SessionFactory.class).openSession();
return currentSession.get(ClientAccount.class, id);
}
BankAccountServiceImpl和ClientAccountServiceImpl: aitowired BankAccountDaoImpl和ClientAccountDaoImp
所有方法都具有@Transactional批注:
@Override
@Transactional
public void saveClientAccount(ClientAccount clientAccount) {
clientAccountDao.saveClientAccount(clientAccount);
}
@Override
@Transactional
public ClientAccount getClientAccount(int id) {
return clientAccountDao.getClientAccount(id);
}
我有@RestController:
@GetMapping("/buy/{accountId}/sum/{money}")
public ClientAccount chargeAccount(@PathVariable int accountId,
@PathVariable int money) {
BankAccount bankAccount = bankAccountService.getBankAccount(1);
int mn = bankAccount.getAmount() - money;
bankAccount.setAmount(mn);
bankAccountService.saveBankAccount(bankAccount);
ClientAccount clientAccount = clientAccountService.getClientAccount(accountId);
clientAccount.setAmount(money);
clientAccountService.saveClientAccount(clientAccount);
return clientAccount;
}
在方法中
clientAccountService.saveClientAccount(clientAccount)
;
我有一个例外:
org.hibernate.HibernateException:非法尝试关联 具有两个打开的会话的代理[com.sustavov.bank.entity.Client#1]
如果在Dao课堂中,我会做getCurrentSession()
,但openSession()
除外。
我有一个错误:
javax.persistence.TransactionRequiredException:没有事务在 进度