简体   繁体   中英

CDI JPA Generic Dao

I have BaseEntity class.

@MappedSuperclass
public class BaseEntity {

private String userId;

public String getUserId() {
        return userId;
}

public void setUserId(String userId) {
        this.userId = userId;
}

}

I have Dao Interface.

public interface IBaseDao<T extends BaseEntity, ID extends Serializable> {
    T persist(T entity);
}

I have AbstractDao implements IBaseDao.

public abstract class GenericBaseDao<T extends BaseEntity, ID extends Serializable> implements IBaseDao<T, ID> {
    public T persist(T entity) {
        getEntityManager().persist(entity);

        return entity;
    }
}

I can write my own custom dao class which extends GenericBaseDao and marked it @ApplicationScoped.

public interface IRoleDao extends IBaseDao<Role, Long> {

}

@ApplicationScoped
@Named
public class RoleDaoImpl extends GenericBaseDao<Role, Long> implements IUserDao {

}

Everything works fine.

I have dao annotation

@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD, ElementType.TYPE })
public @interface Dao {

}

Instead of creating dao java class, i want to use this annotation to create specified dao at injection point on the fly.

@Inject
@Dao
private GenericDao<Role, Long> roleDao;

I want to produce application scoped bean for roleDao on the fly. To accomplish this, i create GenericDao class.

public class GenericDao<T extends BaseEntity, ID extends Serializable> extends GenericBaseDao<T, ID> {
}

can someone explain how to produce genericDao and should be in applicationscoped not dependant. is this the best practice to create generic dao rather than creating my own Dao java class.

Any help appreciated!

Don't do this.

Creating and injecting a generic DAO is not a good (nor simple, due to type erasure ) way to go. You may ask "Why?". Because each DAO has almost always completely different methods than other DAOs. The only generic methods, common to all, are probably: findById , findAll , save , count , delete etc.

I've already answered very similar question here (it was about Spring, but idea remains the same).

If you want details, then please read the mentioned earlier answer.

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