Java 无法从SpringBoot主方法保存JPA存储库变量的方法

Java 无法从SpringBoot主方法保存JPA存储库变量的方法,java,spring-boot,jpa,Java,Spring Boot,Jpa,我已经创建了一个简单的SpringBoot应用程序,在启动时调用api后将数据加载到db中 我的存储库看起来像 import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; @Repository public interface EmployeeRepository extends CrudRepository<Employee,

我已经创建了一个简单的SpringBoot应用程序,在启动时调用api后将数据加载到db中

我的存储库看起来像

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;


@Repository
public interface EmployeeRepository extends CrudRepository<Employee, Long> {

}
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import java.util.Date;

@Entity
@Table(name = "employees")
@EntityListeners(AuditingEntityListener.class)
@JsonIgnoreProperties(value = {"createdAt", "updatedAt"}, 
        allowGetters = true)
public class Employee {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotBlank
    private String email;

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getFirst_name() {
        return first_name;
    }

    public void setFirst_name(String first_name) {
        this.first_name = first_name;
    }

    public String getLast_name() {
        return last_name;
    }

    public void setLast_name(String last_name) {
        this.last_name = last_name;
    }

    @NotBlank
    private String first_name;

    @NotBlank
    private String last_name;

    @Column(nullable = false, updatable = false)
    @Temporal(TemporalType.TIMESTAMP)
    @CreatedDate
    private Date createdAt;

    @Column(nullable = false)
    @Temporal(TemporalType.TIMESTAMP)
    @LastModifiedDate
    private Date updatedAt;

    public Employee(@NotBlank String email, @NotBlank String first_name, @NotBlank String last_name) {
        this.email = email;
        this.first_name = first_name;
        this.last_name = last_name;
    }


}
现在,我将存储库调用到主Springboot方法中

import java.util.Map;

    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
    import org.springframework.http.HttpEntity;
    import org.springframework.http.HttpHeaders;
    import org.springframework.http.HttpMethod;
    import org.springframework.http.MediaType;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.client.RestTemplate;

    import com.example.demo.model.Employee;
    import com.example.demo.repository.EmployeeRepository;
    import com.google.gson.Gson;
    import com.google.gson.reflect.TypeToken;

    @SpringBootApplication
    @EnableJpaAuditing
    public class DemoApplication {
         static EmployeeRepository empr;

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

        private static void getEmployees()
        {
            final String uri = "https://reqres.in/api/users";

            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
            headers.add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36");
            HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);

            ResponseEntity<String> response = restTemplate.exchange(uri, HttpMethod.GET,entity, String.class);

            String data = response.getBody();
            Map<String, Object> employees = new Gson().fromJson(
                    data, new TypeToken<Map<String, Object>>() {}.getType()
                );
            InsertEmployee((ArrayList<Map<String, String>>) employees.get("data"));
    //        Type type = new TypeToken<Map<String, ArrayList>>() {}.getType();
    //        Gson gson = new Gson();
    //        Map<String,ArrayList> emps =gson.fromJson(data, type);
            //ArrayList empData = (ArrayList) respData.get("Data");
            System.out.println(employees.get("data"));
        }


        private static void InsertEmployee(ArrayList<Map<String, String>> employees) {
            // TODO Auto-generated method stub


            for(Map<String,String> e: employees) {
                System.out.println(e.get("first_name"));
                System.out.println(e.get("email"));
                System.out.println(e.get("last_name"));

                Employee emp = new Employee(e.get("email"), e.get("first_name"), e.get("last_name"));

                empr.save(emp);
            }
        }
    }

不,不要那样做。Spring不会注入
静态
bean。
我建议您创建另一个类,比如
EmployeeInitializer
,它实现
CommandLineRunner

有一种方法可以让你在应用程序启动时做你想做的事情

@Component
public class EmployeeInitializer implements CommandLineRunner{

    @Override
    public void run (...){
      // do job here
    }
}

给定的实现也是正确的,您只需对实现进行一些小的更改,请查看-

import java.util.Map;

    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
    import org.springframework.http.HttpEntity;
    import org.springframework.http.HttpHeaders;
    import org.springframework.http.HttpMethod;
    import org.springframework.http.MediaType;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.client.RestTemplate;

    import com.example.demo.model.Employee;
    import com.example.demo.repository.EmployeeRepository;
    import com.google.gson.Gson;
    import com.google.gson.reflect.TypeToken;

    @SpringBootApplication
    @EnableJpaAuditing
    public class DemoApplication {

        @Autowired
        private EmployeeRepository empr;

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

        @PostConstruct 
        private void getEmployees()
        {
            final String uri = "https://reqres.in/api/users";

            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
            headers.add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36");
            HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);

            ResponseEntity<String> response = restTemplate.exchange(uri, HttpMethod.GET,entity, String.class);

            String data = response.getBody();
            Map<String, Object> employees = new Gson().fromJson(
                    data, new TypeToken<Map<String, Object>>() {}.getType()
                );
            InsertEmployee((ArrayList<Map<String, String>>) employees.get("data"));
    //        Type type = new TypeToken<Map<String, ArrayList>>() {}.getType();
    //        Gson gson = new Gson();
    //        Map<String,ArrayList> emps =gson.fromJson(data, type);
            //ArrayList empData = (ArrayList) respData.get("Data");
            System.out.println(employees.get("data"));
        }


        private static void InsertEmployee(ArrayList<Map<String, String>> employees) {
            // TODO Auto-generated method stub


            for(Map<String,String> e: employees) {
                System.out.println(e.get("first_name"));
                System.out.println(e.get("email"));
                System.out.println(e.get("last_name"));

                Employee emp = new Employee(e.get("email"), e.get("first_name"), e.get("last_name"));

                empr.save(emp);
            }
        }
    }
import java.util.Map;
导入org.springframework.boot.SpringApplication;
导入org.springframework.boot.autoconfigure.springboot应用程序;
导入org.springframework.data.jpa.repository.config.EnableJpaAuditing;
导入org.springframework.http.HttpEntity;
导入org.springframework.http.HttpHeaders;
导入org.springframework.http.HttpMethod;
导入org.springframework.http.MediaType;
导入org.springframework.http.ResponseEntity;
导入org.springframework.web.client.rest模板;
导入com.example.demo.model.Employee;
导入com.example.demo.repository.EmployeeRepository;
导入com.google.gson.gson;
导入com.google.gson.reflect.TypeToken;
@SpringBoot应用程序
@启用JPA审核
公共类演示应用程序{
@自动连线
私人雇员安置empr;
公共静态void main(字符串[]args){
run(DemoApplication.class,args);
}
@施工后
私人雇员()
{
最终字符串uri=”https://reqres.in/api/users";
RestTemplate RestTemplate=新RestTemplate();
HttpHeaders=新的HttpHeaders();
setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
添加(“用户代理”、“Mozilla/5.0(Windows NT 10.0;Win64;x64)AppleWebKit/537.36(KHTML,如Gecko)Chrome/54.0.2840.99 Safari/537.36”);
HttpEntity=新的HttpEntity(“参数”,标题);
ResponseEntity response=restemplate.exchange(uri,HttpMethod.GET,entity,String.class);
字符串数据=response.getBody();
Map employees=new Gson().fromJson(
数据,新的TypeToken(){}.getType()
);
InsertEmployee((ArrayList)employees.get(“数据”);
//Type Type=new-TypeToken(){}.getType();
//Gson Gson=新的Gson();
//Map emps=gson.fromJson(数据,类型);
//ArrayList empData=(ArrayList)respData.get(“数据”);
System.out.println(employees.get(“数据”));
}
私有静态void InsertEmployee(ArrayList员工){
//TODO自动生成的方法存根
适用于(地图e:员工){
System.out.println(e.get(“first_name”);
System.out.println(e.get(“email”);
System.out.println(e.get(“姓氏”);
员工emp=新员工(e.get(“电子邮件”)、e.get(“名字”)、e.get(“姓氏”);
emp.save(emp);
}
}
}
希望这对你有帮助


快乐编码:-)

我遇到了一个错误,无法对非静态字段进行静态引用
empr
谢谢你的建议,它工作得很好..真棒的回答你救了我一天,不需要肮脏的编码一个完美的解决方法
import java.util.Map;

    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
    import org.springframework.http.HttpEntity;
    import org.springframework.http.HttpHeaders;
    import org.springframework.http.HttpMethod;
    import org.springframework.http.MediaType;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.client.RestTemplate;

    import com.example.demo.model.Employee;
    import com.example.demo.repository.EmployeeRepository;
    import com.google.gson.Gson;
    import com.google.gson.reflect.TypeToken;

    @SpringBootApplication
    @EnableJpaAuditing
    public class DemoApplication {

        @Autowired
        private EmployeeRepository empr;

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

        @PostConstruct 
        private void getEmployees()
        {
            final String uri = "https://reqres.in/api/users";

            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
            headers.add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36");
            HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);

            ResponseEntity<String> response = restTemplate.exchange(uri, HttpMethod.GET,entity, String.class);

            String data = response.getBody();
            Map<String, Object> employees = new Gson().fromJson(
                    data, new TypeToken<Map<String, Object>>() {}.getType()
                );
            InsertEmployee((ArrayList<Map<String, String>>) employees.get("data"));
    //        Type type = new TypeToken<Map<String, ArrayList>>() {}.getType();
    //        Gson gson = new Gson();
    //        Map<String,ArrayList> emps =gson.fromJson(data, type);
            //ArrayList empData = (ArrayList) respData.get("Data");
            System.out.println(employees.get("data"));
        }


        private static void InsertEmployee(ArrayList<Map<String, String>> employees) {
            // TODO Auto-generated method stub


            for(Map<String,String> e: employees) {
                System.out.println(e.get("first_name"));
                System.out.println(e.get("email"));
                System.out.println(e.get("last_name"));

                Employee emp = new Employee(e.get("email"), e.get("first_name"), e.get("last_name"));

                empr.save(emp);
            }
        }
    }