【发布时间】:2020-03-02 10:46:56
【问题描述】:
我正在使用 Data JPA 在 Spring Boot 中开发简单的 Crud 应用程序,我的目标很简单,我有两个实体:Foo.java
@Data // lombok annotation
@Entity(name = "foos")
public class Foo{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(unique = true, nullable = false)
private Integer fooId;
private String FooName;
@NonNull
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "bar_id")
private List<Bar> barList;
}
Bar.java
@Data
@Entity(name = "bars")
public class Bar{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id", unique = true, nullable = false)
private Integer barId;
private String barTitle;
}
在我的控制器中,我想将 Foo 和 Bars 列表保存为:
@Controller
@RequestMapping(value = "/foo")
public class FooController {
private final FooService fooService;
private final BarService barService;
public FooController(FooService fooService, BarService barService) {
this.fooService = fooService;
this.barService = barService;
}
@GetMapping(value = "/{id}/add_bar")
public String addBar(@PathVariable("id") Integer id, Model model){
model.addAttribute("foo", fooService.findById(id));
model.addAttribute("bar", new Bar());
return "add_bar";
}
@PostMapping(value = "/{id}/add_bar")
public String saveBar(
@PathVariable("id") Integer id,
@ModelAttribute("bar") Bar bar,
BindingResult result
){
if (result.hasErrors()) {
return "add_bar";
}
// update foo by adding new bar and save
Foo foo = getFooAndAddBar(id, bar);
fooService.save(foo);
// save bar
barService.save(bar);
return "redirect:/foo/" + foo.getFooId();
}
// update foo by adding new bar and save
private Foo getFooAndAddBar(Integer id, Bar bar) {
Foo foo = fooService.findById(id);
ArrayList<Bar> barList = new ArrayList<>();
barList.add(bar);
foo.setBarList(barList);
return foo;
}
}
第一个 bar 由 foo id 保存和获取,但是当我想添加另一个 bar 时,它只会更新第一个 bar,而不是在 DB 中插入新的 bar 记录。 @OneToMany 关联是否缺少任何东西?或者程序的其他部分缺少什么?请。
【问题讨论】:
标签: java spring-boot spring-data-jpa hibernate-onetomany