无法从SpringBoot Main方法保存的JPA Repository变量方法

问题描述 投票:0回答:2

我创建了一个简单的spring boot应用程序,它将在调用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;
    }


}

现在我将存储库调用到Main 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);
            }
        }
    }

Got Error Nullpointer异常

Exception in thread "main" java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:48)
        at org.springframework.boot.loader.Launcher.launch(Launcher.java:87)
        at org.springframework.boot.loader.Launcher.launch(Launcher.java:51)
        at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:52)
Caused by: java.lang.NullPointerException
java spring-boot jpa
2个回答
1
投票
不,不要那样做。 Spring将不会注入static bean。我建议您创建另一个类,例如实现EmployeeInitializerCommandLineRunner

-1
投票
给定的实现也是正确的,您只需要对实现进行一些小的更改,请看一下-
© www.soinside.com 2019 - 2024. All rights reserved.