java ee - JPA data access object - exception handling and rollback -


i'd know best way of exception handling in data access objects is, i'm interested in production quality code.

as example

public userdaoimpl implements userdao{     @persistencecontext     private entitymanager em;      void save(user user){        em.persist(user);     }     user getbyid(long id){        return em.find(user.class,id);     } } 

let's example have registerservice somewhere @ point i'd save user database. , each user needs have unique email. how check , code go ? check if there's user email in save method using queries before persisting? or code go service? or maybe try catch exceptions?

but exceptions far know we'd never know sure happened, try catch constraintviolationexception doesn't tell explicitely happened.

how in production quality code?

let's example have registerservice somewhere @ point i'd save user database. , each user needs have unique email. how check , code go ?

check in same transaction you're inserting , throw custom exception triggers full rollback.

checking in same transaction guarantee db won't cause constraint violation exception during insert. proposed "dao" @stateless ejb (based on fact tagged question [java-ee] , not e.g. [spring]), each single method call client counts default single transaction.

throwing custom service layer specific exception decouples frontend (i.e. whoever calling business service method, e.g. jsf, jax-rs, spring mvc, jsp/servlet, etc) underlying persistence layer. in other words, frontend codebase free of javax.persistence.* imports/dependencies. proposed you're using ejb service layer api, annotate custom exception @applicationexception(rollback=true).

e.g.

@stateless public class userservice {      @persistencecontext     private entitymanager em;      public user findbyemail(string email) {         list<user> users = em.createquery("select u user u email = :email", user.class)             .setparameter("email", email)             .getresultlist();         return users.isempty() ? null : users.get(0);     }      public void register(user user) {         if (findbyemail(user.getemail()) != null) {             throw new duplicateentityexception();         }          em.persist(user);     }      // ... } 
@applicationexception(rollback=true) public class duplicateentityexception extends runtimeexception {} 

then, in frontend, catch custom service layer specific exception (which know sure it's expected unexpected condition causing exception) , handle accordingly e.g. showing "hey, you're registered! perhaps want login or reset password?" message enduser.

see also:


Comments

Popular posts from this blog

dns - How To Use Custom Nameserver On Free Cloudflare? -

python - Pygame screen.blit not working -

c# - Web API response xml language -