首页 > 解决方案 > 如何在 Java 程序的开头加载一个表?

问题描述

有一个名为“Employees”的表,其中包含employeeName 和employeeId。我想在程序启动后立即将其加载到 HashMap<string,string> 中,以便其他函数可以访问它。我正在使用弹簧靴。我现在有以下文件,

应用程序.java

@SpringBootApplication
public class Application {

    public static void main(String[] args){
        SpringApplication.run(Application.class,args);
    }
}

IEmployeeRepository.java

@Repository
public interface IEmployeeRepository extends JpaRepository {

    @Query(value = "select * from Employee")
    HashMap<String ,String> EmployeeReferenceTable();
}

IEmployeeRepository 将给出 HashMap。我有另一个名为 EmployeeTable.java 的文件,它应该调用 Repository 并获取整个表。

EmployeeTable.java


public class rdEmployee {


    @Bean
    public HashMap<String, String> EmployeeHashMap(){
        // Should get the HashMap from Repository file.

    }

}

除此之外,还有一些文件需要上述 Employee Table 值。怎么做?我做得对吗?使用 Bean 注释,以便在程序开始时完成。是否正确使用?IEmployeeRepository 是一个接口,那么如何从 EmployeeHashMap() 中调用呢?

标签: javaspringspring-bootjpaspring-data-jpa

解决方案


您应该添加 Class 字段的 @Component 注释,然后使用 @Bean 注释然后在那里实现您的逻辑

@Component  
 public class rdEmployee {


    @Bean
    public HashMap<String, String> EmployeeHashMap(){
        // Should get the HashMap from Repository file.

    }

}

推荐阅读