【问题标题】:wiered behavior of OneToMany relationship while using spring boot and spring data jpa使用spring boot和spring data jpa时一对多关系的奇怪行为
【发布时间】: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;

}

在我的控制器中,我想将 FooBars 列表保存为:

@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


    【解决方案1】:

    每次调用函数时,您都在设置 barlist。你写了foo.setBarList(barList);。每次这将覆盖以前的 barlist,然后保存它,从而覆盖以前的值。而不是这个尝试这个foo.getBarList().add(Bar)。它将获取先前的 bar 列表,然后将新 bar 添加到列表中。在此之后只需保存实体

    【讨论】:

    • 确实是我一直想念的!
    • 旁注:使用三层架构。这将是一个很好的编码实践。阅读MVC
    • 您能否简要介绍一下Three Tier architecture,因为我是网络开发领域的新手。
    • 这是一个不错的视频,它提供了有关 spring mvc youtube.com/watch?v=g2b-NbR48Jo 您可以在 youtube 上找到更多信息
    猜你喜欢
    • 2016-04-14
    • 1970-01-01
    • 1970-01-01
    • 2018-04-14
    • 2017-08-19
    • 1970-01-01
    • 2016-06-22
    • 2019-01-24
    • 1970-01-01
    相关资源
    最近更新 更多