我对java持久性很新。 我的数据库模型有两个表:学生和联系人,每个学生可以有很多紧急联系人,但每个联系人只能属于一个学生。
在我的控制器中,帖子正文被正确地解析为包含联系人对象列表的学生对象。 但是,没有任何内容添加到“联系人”表中,并且学生表中没有添加任何内容,以暗示该学生可以引用联系人列表。可能有一个简单的解决方案,但经过几个小时的搜索,我找不到它。
Controller.java
@RestController
@RequestMapping("/students")
public class StudentController {
@Autowired
StudentRepository studentRepository;
@RequestMapping(method = RequestMethod.POST)
public void submitStudents(@RequestBody Map<Long,Student> students) {
System.out.println("==========Updating database==========");
students.values().forEach(student -> {
System.out.println(student.getContacts().get(0).getParentTitle());
studentRepository.save(student);});
}
}
Student.java
@Entity(name="Student")
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String firstName;
private String lastNames;
@OneToMany(targetEntity = Contact.class, mappedBy = "student", fetch = FetchType.EAGER)
private List<Contact> contacts = new ArrayList<>();
// Spring needs a no-args constructor
public Student() {}
public List<Contact> getContacts() {
return contacts;
}
public void setContacts(List<Contact> contacts) {
this.contacts = contacts;
}
public String getFirstName() {
return firstName;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastNames() {
return lastNames;
}
public void setLastNames(String lastNames) {
this.lastNames = lastNames;
}
// not sure if I really need this, contacts were added to the student object before I had this method
public void addContact(Contact contact) {
System.out.println("adding contact");
contact.setStudent(this);
contacts.add(contact);
}
@Override
public boolean equals(Object object) {
if (!(object instanceof Student)) {
return false;
}
return
this.id == ((Student) object).getId();
}
}
Contact.java
@Entity
public class Contact {
@Id
@GeneratedValue
private Long id;
@ManyToOne
private Student student;
private String phone;
public Contact() {}
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
System.out.println("setting student to "+student);
this.student = student;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Long getId() { return id; }
}
答案 0 :(得分:0)
你需要通过将CascadeType添加到@OneToMany来告诉Hibernate级联:
<?php
$file = file('/home/file.txt');
$selected_tag = implode(PHP_EOL,array_splice($file,5));
$result = implode(PHP_EOL,$file);
echo $result;
?>