gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 09:03:58 25 4
gpt4 key购买 nike

我创建了一个简单的 Spring Boot 应用程序,当它开始启动时,它将在调用 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);
}
}
}

出现错误空指针异常

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

最佳答案

不,不要这样做。 Spring 不会注入(inject)静态 bean。我建议您创建另一个类,例如实现 CommandLineRunnerEmployeeInitializer

CommandLineRunner有一种方法可以让您在应用程序启动时执行您想要的操作。

@Component
public class EmployeeInitializer implements CommandLineRunner{

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

关于java - JPA Repository 变量的方法无法从 SpringBoot Main 方法保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59967647/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com