无法在泛型类中调用实体保存

时间:2013-02-18 21:42:31

标签: java generics service dao

public class JobAssetService extends GenericService<JobAssetService, JobAsset, JobAssetDao> {

}

我正在尝试为我的服务层提供通用的save()功能,但它似乎不喜欢我传递给dao.save()的内容。这似乎应该有用......

不兼容的类型 要求:M 发现:java.lang.object

public class GenericService<T, M, Dao extends GenericDao> {

    protected Dao dao;
    protected EntityManager em;

    public GenericService() {

    }

    //map the dao/entity manager when instantiated
    public GenericService(Class<Dao> daoClass) {
        //map entity manager & dao
        //code removed for readability
    }

    public M save(M entity) {
        EntityTransaction tx = em.getTransaction();
        tx.begin();
        entity = dao.save(entity); //IntelliJ complains about this
        tx.commit();

        return entity;
    }
}

2 个答案:

答案 0 :(得分:1)

在IntellijIDEA中你可以把光标放在错误上,然后使用ALT + ENTER和intellij可能会建议你施放

的结果
dao.save(entity)

为“M”

entity = (M) dao.save(entity); 

答案 1 :(得分:1)

你应该GenericDao使用泛型:

class GenericDao<M> {
    public M save(M entity) {
        ...
    }
}

然后按如下方式扩展您的通用服务:

public class GenericService<T, M, Dao extends GenericDao<M>> {