CDI Generic Dao


Just added multiple datasources support to our example application, see here details:



I’ve revisited this post some days ago and refactored the code, of course i keeped everything here and the github repo untouched so you can folow this post. Instead i’ve created a new github repository to share the new code there, i have updated the apis, added some (arquillian)tests, new functionality like true pagination and new apis(hibernate and deltaspike) and now it works on wildfly, Glassfish and Jboss7. I’ve also changed a bit of the project structure but the idea is the same, the code can be found here: cdi-crud.


In this post i will show how to implement basic CRUD operations using a generic dao based on CDI beans. Its not the purpose to discuss about the Dao pattern itself, there are already long discussions about it see[1],[2],[3] and [4]. For a good and detailed introduction about the pattern see [5].

The source code can be found here: and also as usual there is a video produced by this post here:

Show me the code

lets get hands dirty with some code, here is the classic BaseEntity which in this case will hold only the primary key of our JPA entities:

public abstract class BaseEntity<ID> {

    @GeneratedValue(strategy = GenerationType.AUTO)
    private ID id;

    public ID getId() {
        return id;

    public void setId(ID id) { = id;


Next is the simple Car entity:

public class Car extends BaseEntity<Integer>{

    private String model;
    private Double price;

 //getter & setters

Now the so called generic dao:

public class<T extends BaseEntity<ID>, ID>> implements Serializable {

    private EntityManager entityManager;
    private Class entityClass;

    public EntityManager getEntityManager() {
        return entityManager;

    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;

    public Class getEntityClass() {
        if (entityClass == null) {
            //only works if one extends BaseDao, we will take care of it with CDI
            entityClass = (Class) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        return entityClass;

    public void setEntityClass(Class entityClass) {
        this.entityClass = entityClass;

    //utility database methods
    public T find(ID id) {
        return (T) this.entityManager.find(getEntityClass(), id);

    public void delete(ID id) {
        Object ref = this.entityManager.getReference(getEntityClass(), id);

    public T update(T t) {
        return (T) this.entityManager.merge(t);

    public void insert(T t) {

    public List findAll() {
        return entityManager.createQuery("Select entity FROM "+getEntityClass().getSimpleName() +" entity").getResultList();
//more utility methods

It is an usual dao, it has a PersistenceContext injected by the EJB container, it’s a Stateless Session Bean, have some utility database methods but it cannot work alone, you need to feed it with an Entity so it can perform database operations.

There are several ways to provide an entity to a generic dao, via constructor, annotation, extending it etc. In this example we provide the Entity by two manners, extending it and via CDI producer.

Extending the Dao

Here is a generic dao specialization, the CarDao:

public class CarDao extends BaseDao<Car, Integer>{
    //put here specific car business

The entity is passed to BaseDao in getEntityClass() via ParameterizedType and now we can inject our dao in any bean:

public class SomeBean{
    CarDao carDao;

    public void createCar(Car car){

this is good cause you usually will extend the base dao to add some more complex operations then CRUD but sometimes you just need the CRUD and you will have to create empty daos extending the BaseDao just to benefit from its utility methods, what i really want is to inject the BaseDao directly:

   BaseDao<Car,Integer> baseCarDao;

The only thing that prohibits me from doing that is that the ParameterizedType can only be got from a superclass with getGenericSuperclass()(the only way I know 😉 ), at least before CDI came.

Producing the Dao

We are going to set the entity in a CDI producer, to do that we provide a qualifier that will tell CDI we want a produced Dao not the real one, here is the Dao qualifier:

public @interface Dao {

And here is our producer responsible of creating a baseDao with a setted Entity based on the InjectionPoint ParameterizedType:

public class DaoProducer implements Serializable {

    private static final long serialVersionUID = 1L;

    @Dependent//must be dependent pseudoScope cause baseDao is a SLB
    public <ID, T extends BaseEntity> BaseDao<T, ID> produce(InjectionPoint ip, BeanManager bm) {
        if (ip.getAnnotated().isAnnotationPresent(Dao.class)) {
            BaseDao<T, ID> genericDao = (BaseDao<T, ID>)  this.getBeanByName("baseDao", bm);//ask bean manager for a instance of GenericDao
            ParameterizedType type = (ParameterizedType) ip.getType();
            Type[] typeArgs = type.getActualTypeArguments();
            Class<T> entityClass = (Class<T>) typeArgs[0];
            return genericDao;
        throw new IllegalArgumentException("Annotation @Dao is required when injecting BaseDao");

    public Object getBeanByName(String name, BeanManager bm) { // eg. name=availableCountryDao{
        Bean bean = bm.getBeans(name).iterator().next();
        CreationalContext ctx = bm.createCreationalContext(bean); // could be inlined below
        Object o = bm.getReference(bean, bean.getBeanClass(), ctx); // could be inlined with return
        return o;


The ‘secret’ here is that we are infering the Dao’s entity in InjectionPoint so when we Inject BaseDao with:

  @Inject @Dao BaseDao<User,Long> baseUserDao;

the (Class<T>) typeArgs[0]; in line 13 will return User.class and we set it in the Dao. Below is a concrete bean using our Dao to perform crud operations:

public class CarBean implements Serializable{

    private List carList;
    private List filteredValue;//datatable filteredValue attribute
    private Integer id;
    private Car car;

    @Inject CarDao carDao;

    @Inject @Dao
    BaseDao<Car,Integer> genericDao;//reuse generic dao for basic crud operation in various entities
//    @Inject @Dao
//    BaseDao<Person,Long> genericDao;
//    @Inject @Dao
//    BaseDao<Client,IDClass> genericDao;

    public void init(){
            for (int i = 1; i < 10; i++) {
                Car c = new Car("Car"+i, i);
        //same as above
//         if(carDao.findAll().isEmpty()){
//            for (int i = 0; i < 10; i++) {
//                Car c = new Car("Car"+i, i);
//                carDao.insert(c);
//            }
//        }


    public List getCarList(){
        if(carList == null){
            carList = carDao.findAll();
        return carList;

    public Integer getId() {
        return id;

    public void setId(Integer id) { = id;

    public Car getCar() {
        if(car == null){
            car = new Car();
        return car;

    public void setCar(Car car) { = car;

    public void findCarById(Integer id){
         car = genericDao.find(id);

    public List getFilteredValue() {
        return filteredValue;

    public void setFilteredValue(List filteredValue) {
        this.filteredValue = filteredValue;

    public void remove(){
        if(car != null && car.getId() != null){
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Car "+car.getModel() +" removed successfully"));

    public void update(){
        String msg;
        if(car.getId() == null){
             msg = "Car "+car.getModel() +" created successfully";
           msg = "Car "+car.getModel() +" updated successfully";
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(msg));
        clear();//reload car list

    public void clear(){
        car = new Car();
        carList = null;
        id = null;

    public void onRowSelect(SelectEvent event) {
        setId(((Car) event.getObject()).getId());

    public void onRowUnselect(UnselectEvent event) {
        car = new Car();


Just a small addendum(which is not that small) there was an issue with the above implementation which showed up when using BaseDao to crud more than one entity in the same bean. The bug was caused because i was storing EntityClass in a stateless session bean(BaseDao), although CDI produces different instances for each injection point the container was returning the same session bean(from the pool of BaseDaos) for each produced bean. The solution was to remove EntityClass from BaseDao and put it in a CDI Bean called CrudDao which has a composion association with BaseDao making it really stateless(as it should be).Here is the CrudDao:

public class CrudDao<T extends BaseEntity<ID>, ID> implements Serializable{

    protected BaseDao<T,ID> dao;

    protected Class<T> entityClass;

   public Class<T> getEntityClass() {
        if (entityClass == null) {
            //only works if one extends CrudDao, we will take care of it with CDI
            entityClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        return entityClass;

    public void setEntityClass(Class<T> entityClass) {
        this.entityClass = entityClass;

    public EntityManager getEntityManager(){
        return dao.getEntityManager();

    public T find(ID id){
        return dao.find(id, getEntityClass());

    public void delete(ID id){
         dao.delete(id, getEntityClass());

    public T update(T t){
        return dao.update(t);

    public void insert(T t){

    public List<T> findAll(){
        return dao.findAll(getEntityClass());

    public List<T> findWithNamedQuery(String namedQueryName){
        return dao.findWithNamedQuery(namedQueryName);





[4] [PT_BR]



26 thoughts on “CDI Generic Dao

  1. Hi sugam,

    do you have any example? as a newbie in spring i google it and found this post:

    looking at it i see a UserRepository which is extending JdbcRepository

    can you for example Inject JdbcRepository directly with Spring?

    something like @Autowire JdbcRepository<User,Long>genericRepository?

    Also note that everything i posted here is for free 😉

    thanks for your comment!


  2. Hi Rafeal,
    You don’t inject the repository directly you extend the interface and inject that new interface. This allows the Spring Data infrastructure to scan the classpath and create a spring bean for it. You don’t physically implement the interface yourself so injecting an interface that extends the repository should not make any difference to you. By extending the interface you can add attribute finder methods that Spring Data will then implement for you. (This was what I meant by for free – that Spring Data provides the implementations for you without you having to write any implementation code) 🙂


  3. I see(im not so newbie with Spring, already used Spring data ;)), that’s what i’m doing with CarDao, i just extend BaseDao and add no implementation code. what i really focus on this post is to avoid ’empty daos'(or empty Repositories in your case) and i can do that Injecting the generic implementation directly.

    Also note that empty daos are not common you usually will add some extra functionality, even when cruding.

    Thanks again!


  4. During deploy on Glassfish 4 I get following exception:

    2014-05-16T14:21:55.295+0200|Info: Computed the following CODI ProjectStage: Production
    2014-05-16T14:21:55.700+0200|Severe: Exception during lifecycle processing
    org.glassfish.deployment.common.DeploymentException: CDI deployment failure:WELD-001408 Unsatisfied dependencies for type [Validator] with qualifiers [@Default] at injection point [[UnbackedAnnotatedField] @Inject private org.hibernate.validator.internal.cdi.interceptor.ValidationInterceptor.validator]
    at org.glassfish.weld.WeldDeployer.event(
    at org.glassfish.kernel.event.EventsImpl.send(
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(
    at org.glassfish.deployment.admin.DeployCommand.execute(
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$
    at Method)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2.execute(
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1500(
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(
    at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(
    at com.sun.enterprise.v3.admin.AdminAdapter.onMissingResource(
    at org.glassfish.grizzly.http.server.StaticHttpHandler.service(
    at org.glassfish.grizzly.http.server.HttpHandler.runService(
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(
    at org.glassfish.grizzly.ProcessorExecutor.execute(
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$
    Caused by: org.jboss.weld.exceptions.DeploymentException: WELD-001408 Unsatisfied dependencies for type [Validator] with qualifiers [@Default] at injection point [[UnbackedAnnotatedField] @Inject private org.hibernate.validator.internal.cdi.interceptor.ValidationInterceptor.validator]
    at org.jboss.weld.bootstrap.Validator.validateInjectionPointForDeploymentProblems(
    at org.jboss.weld.bootstrap.Validator.validateInjectionPoint(
    at org.jboss.weld.bootstrap.Validator.validateInterceptor(
    at org.jboss.weld.bootstrap.Validator.validateInterceptors(
    at org.jboss.weld.bootstrap.Validator.validateDeployment(
    at org.jboss.weld.bootstrap.WeldBootstrap.validateBeans(
    at org.glassfish.weld.WeldDeployer.event(
    … 36 more


  5. Pingback: CDI Crud Multi Tenancy | Rafael Pestano
  6. Hi Rafael,

    I have tried your example with CarDao extending the BaseDao, it works like a charm.
    However, from the CarDao class, my NetBeans underlined the class name “CarDao” with the
    error message “A session bean must not extend another session bean.” But I can compile,
    deploy and run the application without any problem.
    I have also heard that a session bean cannot extend another session bean, but why it works here?

    I am using NetBeans 8.0.1 and WebLogic 12c for this code testing.


    Liked by 1 person

  7. Pingback: Some Words on JavaEE, REST and Swagger | Rafael Pestano
  8. Hi, good explanation, i have tried this as you mentioned and getting below error. Any help would be appreciated.

    Caused by: org.jboss.weld.exceptions.DeploymentException: WELD-001408 Unsatisfied dependencies for type [GenericBaseDao] with qualifiers [@JpaDao] at injection point [[field] @JpaDao @Inject private rest.service.EntitlementsServiceEJB.userDao]


  9. Hi Rafael! I get this exception while building:

    — jaxrs-analyzer-maven-plugin:0.15:analyze-jaxrs (default) @ cdi-crud —
    ago 14, 2017 5:20:21 PM org.sonatype.guice.bean.reflect.Logs$JULSink warn
    ADVERTENCIA: Error injecting: com.sebastian_daschner.jaxrs_analyzer.maven.JAXRSAnalyzerMojo Guice provision errors:

    1) No implementation for org.eclipse.aether.RepositorySystem was bound.
    while locating com.sebastian_daschner.jaxrs_analyzer.maven.JAXRSAnalyzerMojo

    1 error
    at org.sonatype.guice.bean.reflect.AbstractDeferredClass.get(
    at org.sonatype.guice.plexus.lifecycles.PlexusLifecycleManager.onProvision(
    at org.sonatype.guice.bean.locators.LazyBeanEntry.getValue(
    at org.sonatype.guice.plexus.locators.LazyPlexusBean.getValue(
    at org.codehaus.plexus.DefaultPlexusContainer.lookup(
    at org.codehaus.plexus.DefaultPlexusContainer.lookup(
    at org.apache.maven.plugin.internal.DefaultMavenPluginManager.getConfiguredMojo(
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(
    at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(
    at org.apache.maven.DefaultMaven.doExecute(
    at org.apache.maven.DefaultMaven.execute(
    at org.apache.maven.cli.MavenCli.execute(
    at org.apache.maven.cli.MavenCli.doMain(
    at org.apache.maven.cli.MavenCli.main(
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(
    at java.lang.reflect.Method.invoke(
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(

    Any idea how can I fix this? Thanks in advance, and you did a very nice work here!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s