java - Update object and get old value via JPA -
i want log changes of account. therefore, have created entity class shall log changes. each time, account entity saved or updated logging object created.
when object updated new balance old balance shall retrieved database. object bound session retrieving old balance not trivial, because 1 gets new balance.
to circumvent, detached object session. yet, seems workaround should avoided.
the following code snippets shall illustrate scenario.
any suggestion highly appreciated!
the test:
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()))); } }
the service of domain class logged:
@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); } }
the service of logging class:
@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; } }
the class of objects logged:
@data @noargsconstructor @allargsconstructor @entity public class account { @id @generatedbalance protected long id; double balance; }
the logging class:
@data @noargsconstructor @allargsconstructor @entity public class changeaccountlog { @id @generatedbalance private long id; private double oldbalance; private double newbalance; }
you might want use hibernate envers create versioning table instead of creating separate log objects.
Comments
Post a Comment