java - implementing a dao class properly to manage transactions -
i working on java web application calls database backend through hibernate.i use servlets,jsp , tomcat test/deployment.most books on java-ee suggested using dao classes database calls.as per examples given in books(hibernate recipes gary mak),i created generic base class , specific subclass below.
class basedao{ private class persistentclass; public basedao(class persistentclass) { super(); this.persistentclass = persistentclass; } public object findbyid(long id) { sessionfactory factory = hibernateutil.getsessionfactory(); session session = factory.opensession(); object object = null; try { object = (object) session.get(persistentclass, id); return object; } { session.close(); } } @override public void saveorupdate(object obj) { sessionfactory factory = hibernateutil.getsessionfactory(); session session = factory.opensession(); transaction tx = null; try { tx = session.begintransaction(); session.saveorupdate(obj); tx.commit(); }catch(hibernateexception e){ if (tx != null) { tx.rollback(); } throw e; }finally { session.close(); } } } class saleorderdao extends basedao{ public saleorderdao() { super(saleorder.class); } @override public saleorder findsaleorderbyid(long saleorderid){ saleorder = (saleorder)findbyid(saleorderid); return so; } @override public void saveorupdatesaleorder(saleorder so){ saveorupdate( so); } }
while going through posts in forum ,i came across ryan stewart's advice beginning , ending transactions in dao method not recommended..sadly, project not use web framework supports transaction management..and limited using jsp,servlets , servlet container..
is there way can rewrite dao implementations sothat transactions can managed properly..i couldn't find in regard books read..
hope helps me suggestions
sincerely,
jim
normally transactions should not handled in dao. should handled service layer. 1 service method may include multiple dao calls in same transaction.
spring (as other di frameworks) allows annotating service methods @transactional
. without spring can still manually in service layer
Comments
Post a Comment