使用Generics时使用Spring Data存储库时遇到问题

时间:2016-07-23 07:12:40

标签: java spring generics

获取编译错误如下

*Inferred type 'my.domain.model.CustomerDemographicsBasicDetails' for type parameter S is not within its bounds; should extend capture <? extends my.domain.model.CustomerDemographicsBasicDetails>*

customerBasicDetailsRepository(details.getClass()).save(details);

对于以下通用存储库合同

package my.domain.model;

import java.util.List;

public interface CustomerBasicDetailsRepository<T extends CustomerDemographicBasicDetails> {

    List<T> findAll(Iterable<String> customerIds);

    <S extends T> S save(S entity);

    T findOne(String customerId);

    boolean exists(String customerId);

    void delete(T entity);
}

和相应的JpaRepository实现

package my.infrastructure.persistence.jpa;

import my.domain.model.CustomerBasicDetailsRepository;
import my.domain.model.CustomerDemographicBasicDetails;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface JpaCustomerBasicDetailsRepository<T extends CustomerDemographicBasicDetails>
        extends JpaRepository<T, String>,
        CustomerBasicDetailsRepository<T> {

    @Override
    List<T> findAll(Iterable<String> customerIds);

    @Override
    <S extends T> S save(S entity);

    @Override
    T findOne(String customerId);

    @Override
    boolean exists(String customerId);

    @Override
    void delete(T entity);
}

以及下面的域模型类型

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@DiscriminatorColumn(name = "CUSTOMER_TYPE")
@Table(name = "******")
@Access(AccessType.FIELD)
public class CustomerDemographicBasicDetails {

}

@Entity
@DiscriminatorValue("BUS")
@Table(name = "********")
@Access(AccessType.FIELD)
public class BusinessCustomer extends CustomerDemographicBasicDetails {
}

@Entity
@DiscriminatorValue("IND")
@Table(name="******")
@Access(AccessType.FIELD)
public class IndividualCustomer extends CustomerDemographicBasicDetails {
}

和下面的存储库查找工厂方法

public static <T extends CustomerDemographicBasicDetails> CustomerBasicDetailsRepository<T> customerBasicDetailsRepository(Class<T> type) {
    return (CustomerBasicDetailsRepository<T>) applicationContext.getBean(CustomerBasicDetailsRepository.class);
}

0 个答案:

没有答案