我想记录帐户的更改。因此,我创建了一个记录更改的实体类。每次保存或更新帐户实体时,都会创建一个日志记录对象。
当使用新余额更新对象时,应从数据库中检索旧余额。由于对象绑定到会话,因此检索其旧余额并非易事,因为总是会获得新余额。
为了规避,我将对象从会话中分离出来。然而,这似乎是一种应该避免的解决方法。
以下代码片段应说明该场景。
任何建议都非常感谢!
考试:
public class AccountServiceTest
{
@Autowired
AccountService accountService;
@Autowired
ChangeAccountService changeAccountService;
@Test
public void shouldHaveChangeLog()
{
Account account = this.accountService.updateAccount(new Account(0, 10.0));
assertThat(account.getId(), is(not(0L)));
account.setBalance(20.0);
account = this.accountService.updateAccount(account);
final List<ChangeAccountLog> changeResultLogs = this.changeAccountService.findAll();
assertThat(changeResultLogs.get(1).getNewBalance(), is(not(changeResultLogs.get(1).getOldBalance())));
}
}
要记录的域类的服务:
@Service
public class AccountService
{
@Autowired
AccountRepository accountRepository;
@Autowired
ChangeAccountService changeAccountService;
public Account findById(final long id)
{
return this.accountRepository.findOne(id);
}
public Account updateAccount(final Account account)
{
this.changeAccountService.saveLog(account);
return this.accountRepository.save(account);
}
}
日志类的服务:
@Service
public class ChangeAccountService
{
@Autowired
AccountService accountService;
@Autowired
ChangeAccountLogRepository repository;
public ChangeAccountLog save(final ChangeAccountLog changeAccountLog)
{
return this.repository.save(changeAccountLog);
}
public List<ChangeAccountLog> findAll()
{
return this.repository.findAll();
}
public ChangeAccountLog saveLog(final Account account)
{
final Double oldAccountBalance = oldAccountBalance(account);
final Double newAccountBalance = account.getBalance();
final ChangeAccountLog changeAccountLog = new ChangeAccountLog(0, oldAccountBalance, newAccountBalance);
return this.repository.save(changeAccountLog);
}
@PersistenceContext
EntityManager em;
private Double oldAccountBalance(final Account account)
{
this.em.detach(account);
final Account existingAccount = this.accountService.findById(account.getId());
if (existingAccount != null)
{
return existingAccount.getBalance();
}
return null;
}
}
要记录的对象的类:
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class Account
{
@Id
@GeneratedBalance
protected long id;
Double balance;
}
日志记录类:
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class ChangeAccountLog
{
@Id
@GeneratedBalance
private long id;
private Double oldBalance;
private Double newBalance;
}