如何使用ManyToOne关系将JSON转换为POJO? [英] How to convert JSON to POJO with ManyToOne relationship?

查看:173
本文介绍了如何使用ManyToOne关系将JSON转换为POJO?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个与另一个实体双向 @OneToMany 关系的实体。下面是它的外观:

  @Entity 
@Table
public class Foo {
@ Id
@GeneratedValue
整数foo_id;

@OneToMany
@JoinColumn(name =FOO_ID)
Set< Bar>酒吧;
}

@Entity
@Table
public class Bar {
@Id
@GeneratedValue
整数bar_id;

@ManyToOne
@JoinColumn(name =FOO_ID)
Foo foo;

$ / code>

如何保存 Foo 使用 CrudRepository 设置的 bars 对象。例如,我将这个JSON反序列化为一个 Foo 对象:

> {
foo_id:1,
bars:[{bar_id:1},
{bar_id:2}]
}

我需要设置 Foo 变量吗?



如果我需要为每个 Bar save()函数调用c>,那么是否有办法启动一个事务,以便所有这些插入操作都是原子的?

首先,你应该像这样映射关系:

$ $ p $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $设置<酒吧及GT;酒吧;

级联类型取决于您的需求。请阅读文章,以获取更多信息。级联类型。



然后,您可以像这样保存Foo实体:

  Foo foo = new Foo(); 
设置< Bar> bars = new HashSet<>();
Bar bar = new Bar();
bar.setFoo(foo);
bars.add(bar);
foo.setBars(bars);
fooRepositoy.save(foo);


I have an entity that is structured with a bidirectional @OneToMany relationship with another entity. Here's how it looks:

@Entity
@Table
public class Foo {
    @Id
    @GeneratedValue
    Integer foo_id;

    @OneToMany
    @JoinColumn(name = "FOO_ID")
    Set<Bar> bars;
}

@Entity
@Table
public class Bar {
    @Id
    @GeneratedValue
    Integer bar_id;

    @ManyToOne
    @JoinColumn(name = "FOO_ID")
    Foo foo;
}

How do I save a Foo object with the bars set using a CrudRepository? So, for example, I deserialize this JSON into a Foo object:

{
    "foo_id": 1,
    "bars": [{"bar_id": 1},
             {"bar_id": 2}]
}

I need to set the Foo variable somehow?

If I need to use separate save() function calls for each Bar, then is there a way to start a transaction so all these insert operations are atomic?

解决方案

First of all, you should map the relationship like this:

@OneToMany(mappedBy="foo", cascade=CascadeType.PERSIST)
Set<Bar> bars;

The cascade type will depend on your needs. Read this article for further information on cascade types.

Then, you can save the Foo entity like this:

Foo foo = new Foo();
Set<Bar> bars = new HashSet<>();
Bar bar = new Bar();
bar.setFoo(foo);
bars.add(bar);
foo.setBars(bars);
fooRepositoy.save(foo);

这篇关于如何使用ManyToOne关系将JSON转换为POJO?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆