简体   繁体   中英

Generic DAO - “Never go full generic!”

Ive seen allot of usages of generic dao over the internet. you gotta love it:

public interface GenericDao <T, PK extends Serializable> {}

public class GenericDaoHibernateImpl <T, PK extends Serializable>
implements GenericDao<T, PK>

a new class appeared? no problem:

public interface NewClassDao extends GenericDao<NewClass, Long> 

and we're all set.

now, how bad is it if i go "full-generic" and do something like:

public interface FullGenericDao 

public class FullGenericDaoHibernateImpl

now i can only use one DAO (of Object with casting!)

a new class appeared again? no problem:

NewClassApperedAgain newClassAppeared = (NewClassApperedAgain) FullGenericDao.getItemById(20, NewClassApperedAgain.class);

two questions comes to mind:

1) Is it even possible to go "full-generic" and actually create such a DAO? I mean i dont see why not passing for every method of the dao the className and just do the casting neccessary? save(object,className); delete(object,className); etc..

2) What are the Cons (i'm sure there are) of such practice?

thanks!

DAO objects are there to contain domain model specific logic connected with persistence layer.

You can go full generic , but then you have to face questions like:

  • Where should I put the logic connected with searching (eg constructing WHERE clause)?
    • User findUserByOrganizationId(Serializable organizationId)
  • Where do I put some specific mapping functions (eg aggregate queries)?
    • Map<Organization, Integer> findUserCountPerOrganization()

I am pretty sure there are other architectural / logical issues. Also the generics will be erased during the runtime so you have introduced the necessity to include domain object Class<?> in every method signature.

TL;DR it is possible to "go full generic", but you will need to move non-shared persistence logic to the higher levels. It is better to do the shared generic logic in some AbstractDaoImpl and then subclass that. You might end up with empty implementations (the generic superclass might have all you need), but you will have place for future domain model specific methods.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM