我有这两个实体。添加Spring Data Repository禁用功能
@Entity
public class Person {
@Id @GeneratedValue
private Long id;
private String name;
@ManyToOne(cascade=CascadeType.ALL)
private Location location;
public Person() {
}
@Entity
public class Location {
@Id @GeneratedValue
private Long id;
private String place;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "location")
private Set<Person> persons;
public Location() {
}
我也有这个控制器。
@Controller
public class PersonController {
private final PersonRepository repo;
public PersonController(PersonRepository repo) {
this.repo = repo;
}
@GetMapping("/")
public String newPerson(Person person){
return "home";
}
@PostMapping("/")
public String newPerson(Person person, BindingResult result){
repo.save(person);
return "redirect:/person";
}
而这个知识库。
@Repository
public interface PersonRepository extends JpaRepository<Person, Long> {
Optional<Person> findFirstByName(String name);
}
我也有这种支持形式。
<form action="#" th:action="@{/}" th:object="${person}" method="post">
<table>
<tr>
<td>Name:</td>
<td><input type="text" th:field="*{name}" /></td>
</tr>
<tr>
<td>Location:</td>
<td><input type="text" th:field="*{location}" /></td>
</tr>
<tr>
<td><button type="submit">Submit</button></td>
</tr>
</table>
</form>
这一切工作正常,当我提交一些数据。 Person对象被保存,Location对象也被保存。
但是当我添加
@Repository
public interface LocationRepository extends JpaRepository<Location,
Long> {)
位置对象不保存到数据库中,当我提交相同的确切形式。为什么只是添加这个存储库会导致这个问题,解决方案是什么?谢谢。
你可以试试'th:field =“* {location.place}”'? – ledniov
谢谢。这确实解决了这个问题。我认为这是我错过了一些小事。仍然有点想知道为什么表单在没有LocationRepository的情况下工作?我猜测,因为当仓库创建时,Location对象期望一个ID可能被传递。 – Jon
当你填写表单时,并不需要储存库,它们被用来储存数据 – ledniov