Методы переменной репозитория JPA не удалось сохранить из метода SpringBoot Main - PullRequest
0 голосов
/ 29 января 2020

Я создал простое приложение для весенней загрузки, которое будет загружать данные в базу данных после вызова API, когда начнется загрузка

Мой репозиторий выглядит как

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);
            }
        }
    }

Ошибка: исключение 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

Ответы [ 2 ]

1 голос
/ 29 января 2020

Нет, не делай этого. Весна не будет вводить static бобы. Я предлагаю вам создать еще один класс, скажем EmployeeInitializer, который реализует CommandLineRunner.

CommandLineRunner имеет один метод, где вы можете делать то, что вы хотите, когда ваше приложение запускается.

@Component
public class EmployeeInitializer implements CommandLineRunner{

    @Override
    public void run (...){
      // do job here
    }
}
0 голосов
/ 29 января 2020

данная реализация также правильна, вам просто нужно внести небольшие изменения в вашу реализацию, пожалуйста, посмотрите -

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);
            }
        }
    }

В надежде, что это поможет вам

Счастливое кодирование: - )

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...