假设我有一个person的JSON文件(sample.json),显示他们拥有的汽车。我试图将此文件加载到数据库中,但我想创建两个表- PERSON和CAR。我取得了有限的成功。我正在使用Spring Boot Data JPA,我能够插入所有行,但不知何故,'Person &CAR ' s没有反映,因为CAR。Person_id列为空。我应该怎么做才能让这个列正确地填充person_id.
[
{
"name": "Robert",
"cars_owned": [
{
"brand": "Mercedes",
"model": "SLX 500"
},
{
"brand": "Jaguar",
"model": "ZL 300F"
},
{
"brand": "Mercedes",
"model": "CLS 350"
}
]
},
{
"name": "Brenda",
"cars_owned": [
{
"brand": "Honda",
"model": "Accord"
}
]
},
{
"name": "Edward"
}
]
这是我的Person.java
@Entity
@JsonIgnoreProperties(ignoreUnknown = true)
@Table(name = "person")
public class Person {
@Id @GeneratedValue(strategy = GenerationType.AUTO, generator = "uuid4")
private UUID person_id;
private String name;
@OneToMany(mappedBy = "person", cascade = CascadeType.ALL)
private List<Car> cars_owned;
public UUID getPerson_id() {
return person_id;
}
public String getName() {
return name;
}
public void setCars_owned(List<Car> cars_owned) {
this.cars_owned = cars_owned;
}
}
This is my Car.java
@Entity
@Table(name = "cars")
@JsonIgnoreProperties(ignoreUnknown = true)
public class Car {
@Id @GeneratedValue(strategy = GenerationType.AUTO, generator = "uuid4")
private UUID car_id;
private String brand;
private String model;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "person_id")
private Person person;
public UUID getCar_id() {
return car_id;
}
public String getBrand() {
return brand;
}
public String getModel() {
return model;
}
public void setPerson(Person person) {
this.person = person;
}
}
我正在使用这样的commandlinerrunner
@SpringBootApplication
public class TryAppApplication {
private final static Logger LOGGER = LoggerFactory.getLogger(TryAppApplication.class);
public static void main(String[] args) {
SpringApplication.run(TryAppApplication.class, args);
}
@Bean
CommandLineRunner runner(PersonService service) {
return args -> {
ObjectMapper mapper = new ObjectMapper();
TypeReference<List<Person>> typeReference = new TypeReference<>() { };
InputStream inputStream = TypeReference.class.getResourceAsStream("/json/sample.json");
try {
List<Person> persons = mapper.readValue(inputStream, typeReference);
service.save(persons);
LOGGER.info("Saved Persons");
} catch (Exception e) {
//TODO: handle exception
}
};
}
}
程序确实插入了3个人和4辆车,但是汽车。Person_id列为空!我希望它是正确的person_id。任何帮助!
我已经用一个hack修复了它!我不太高兴,因为我认为肯定有比这更好的解决办法。
我基本上修改了我的PersonService.save()函数,如下所示
PersonService.java
public Iterable<Person> save(Iterable<Person> pList) {
for (Person person : pList) {
person.linkCarsToPerson(); // This function in Person class links Car and Person
}
System.out.println(pList);
return repository.saveAll(pList);
}
PersonModel.java
public void linkCarsToPerson() {
if (cars_owned != null && !cars_owned.isEmpty()) {
for (Car car : cars_owned) {
if(car != null) {
car.setPerson(this);
}
}
}
}