使用@MappedSuperclass后Spring Boot应用关闭时出现Repository查询错误
问题分析与解决方案
问题原因
Spring Data JPA默认会扫描所有继承自CrudRepository的接口并尝试创建对应的Repository Bean。你的StatsRepository<T extends Stats>是泛型父接口,虽然子接口(如ChampRepository)关联的是具体@Entity类,但Spring Data JPA依然会尝试为StatsRepository本身创建实例。而Stats是@MappedSuperclass而非@Entity,无法生成有效的JPA查询,因此在上下文初始化阶段抛出错误。
解决方案
1. 标记父Repository接口为@NoRepositoryBean
给StatsRepository添加@NoRepositoryBean注解,明确告诉Spring Data JPA不要为这个接口创建实例,仅作为父类供其他Repository继承:
import org.springframework.data.repository.NoRepositoryBean; import org.springframework.data.repository.CrudRepository; @NoRepositoryBean public interface StatsRepository<T extends Stats> extends CrudRepository<T, StatsId> { List<T> findAllByWeek(int week); List<T> findAllByName(String name); }
2. 优化配置类的Bean定义
调整返回类型为带通配符的泛型,避免泛型类型擦除带来的潜在问题:
@Configuration public class RepositoryConfiguration { @Autowired private ChampRepository champRepository; @Autowired private PsdRepository psdRepository; @Bean public StatsRepository<? extends Stats> repository(League league) { if (league.equals(League.CHAMPIONS)) { return champRepository; } else if (league.equals(League.PSD)) { return psdRepository; } throw new BadInput("The given league is not valid"); } }
验证逻辑
修改后,Spring Data JPA只会为ChampRepository、PsdRepository这类关联具体@Entity类的子接口创建实例,它们可以正常生成查询语句。父接口StatsRepository不会被实例化,也就不会再触发"Stats不是Entity"的错误。
内容的提问来源于stack exchange,提问作者dbrewster
相关产品推荐
相关产品推荐

