无法在 DAO 中自动装配 JpaRepository

Not able to autowire JpaRepository in DAO

我目前正在将 JPA 集成到我以前使用的项目中 HibernateTemplate

我做了以下配置:

@Configuration
@EnableJpaRepositories("package1, package2")
@EnableTransactionManagement
public class JpaConfiguration {


    @Bean
    public EntityManagerFactory entityManagerFactory(){

        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();

        vendorAdapter.getJpaDialect();

        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setJpaVendorAdapter(vendorAdapter);
        factory.setPackagesToScan("package1, package2");
        factory.afterPropertiesSet();

        return factory.getObject();
    }

下面是 class 我试图从中调用存储库但是当我将鼠标悬停在调用上时出现错误说:no-static field applicantEntryRepository cannot be referenced from a static context.

public static PsHeldSkillEntry retrievePsHeldSkillEntry(SkillEntry primaryKey) throws DataAccessException {
    //HibernateTemplate ht = new HibernateTemplate(ComponentBuilder.getSessionFactory());

    //SkillEntry skill = ht.get(SkillEntry.class, primaryKey);

    SkillEntry skill = applicantEntryRepository.getOne(primaryKey);

    return skill;
}


}

applicantEntryRepository 在 class 的顶部自动装配,如下所示:

@Controller
public class ApplicantEntryDAO {

    @Autowired
    ApplicantEntryRepository applicantEntryRepository;

存储库

public interface ApplicantEntryRepository extends JpaRepository<SkillEntry,Long> {


}

实体:

@Entity
@Table(name = "HELD_SKILL")
@IdClass(SkillEntryPK.class)
public class SkillEntry
{

你的问题出在自动装配上,或者 spring 只是 java 问题,你的调用 applicantEntryRepository 在静态方法中不是静态的,你必须先将这个变量设为静态

@Controller
public class ApplicantEntryDAO {

@Autowired
static ApplicantEntryRepository applicantEntryRepository;