CDI producer method for data model

*爱你&永不变心* 提交于 2019-12-06 08:23:47

问题


I'd like to be able to @Inject a data model backing a RichFaces 4 ExtendedDataTable, but it requires an EntityManager to do its work. The EntityManager's queries need to know the Class, of course, and I'd rather not pass that into method calls (in this case the methods are not called by my code); ideally it would be in the constructor.

Something like this:

public class DataModel<T> {
    @Inject private EntityManager em;
    private Class<T> entityClass;

    public DataModel(Class<T> entityClass) {
        this.entityClass = entityClass;
    }

    //Sample method - this class will handle much more complex queries
    public T findEntity(String key) {
        return em.find(entityClass, key);
    }

Is it possible to create a CDI @Producer that can be used to inject this DataModel into my backing beans? I've thought about making a Qualifier so you can do something like

@Inject @JType(value = MyEntity.class) DataModel<MyEntity> dataModel;

But that seemed clumsy, and would also require my @Producer to call new() - which I think would not allow the EntityManager to be injected into the DataModel. Also I'm not sure how you would require the qualifier to be added by the developer.

Or perhaps there's a better way to approach this, and I'm missing something?


回答1:


I do this using the seam-persistence module from seam3. :

Producer :

public class EntityManagerProducer {

   @Produces
   @ExtensionManaged
   @ConversationScoped
   @PersistenceUnit(unitName = "yourUnitName")
   private EntityManagerFactory emf;
}

Then you can @Inject the entity manager.

Otherwise, there is the DeltaSpike project that seems promising (never used it yet)



来源:https://stackoverflow.com/questions/6793756/cdi-producer-method-for-data-model

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!