简体   繁体   English

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

[英]Unable to call save on entity within generic class

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

}

I'm trying to provide generic save() functionality to my service layer but it doesn't seem to like what I'm passing to dao.save() . 我正在尝试向我的服务层提供泛型save()功能,但它似乎不喜欢我传递给dao.save() This seems like this should work... 这似乎应该工作......

Incompatible Types Required: M Found: java.lang.object 不兼容的类型必需:M Found: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;
    }
}

In IntellijIDEA you can put your cursor on the error, then use ALT + ENTER and intellij will probably suggest you to cast the result of 在IntellijIDEA中你可以把光标放在错误上,然后使用ALT + ENTER和intellij可能会建议你施放结果

dao.save(entity)

as "M" 作为“M”

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

you should make GenericDao use generics too: 你应该让GenericDao使用泛型:

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

then extend your generic service as follows: 然后按如下方式扩展您的通用服务:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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