quarkus-panache-onetomany关系不在数据库中持久化

4si2a6ki  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(535)

我目前正在修补一个简单的http资源。我的模型由“树”和多个“果实”组成。两者都继承自泛亚实体。
树:

@Entity
    public class Tree extends PanacheEntity {
    public String name;

    @OneToMany(mappedBy = "tree", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
    public List<Fruit> fruits = new ArrayList<>();
    }

水果

@Entity
    public class Fruit extends PanacheEntity {

    public String name;
    public String color;
    public int cores;

    @ManyToOne
    @JsonbTransient
    public Tree tree;
    }

资源:

import io.quarkus.hibernate.orm.rest.data.panache.PanacheEntityResource;

    public interface TreeResource extends PanacheEntityResource<Tree, Long> { }

这是我通过招摇发送的发帖请求

{
  "name": "Apple Tree",
  "fruits": [
    {
      "color": "green",
      "cores": 3,
      "name": "Apple2"
    },
    {
      "color": "red",
      "cores": 4,
      "name": "Apple"
    }
  ]
}

响应告诉我,ID是为所有对象创建的:

{
  "id": 4,
  "fruits": [
    {
      "id": 5,
      "color": "green",
      "cores": 3,
      "name": "Apple2"
    },
    {
      "id": 6,
      "color": "red",
      "cores": 4,
      "name": "Apple"
    }
  ],
  "name": "Apple Tree"
}

但当我调用get all under/trees时,得到以下响应:

[
  {
    "id": 1,
    "fruits": [],
    "name": "Oak"
  },
  {
    "id": 4,
    "fruits": [],
    "name": "Apple Tree"
  }
]

水果总是空的。检查postgres数据库会发现水果中的所有“tree\u id”列都是空的。我很肯定这是一个初学者的问题,但在检查了多个样本后,我就是找不到我的代码有什么问题。

bxjv4tth

bxjv4tth1#

我也遇到了同样的问题,通过将父对象设置为子对象来解决它。我有job和jobargs项要保留。

// ... somewhere in JobArg.java
    @JsonbTransient
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "job_id", foreignKey = @ForeignKey(name = "job_id_fk"))
    public Job job;
@OneToMany(mappedBy = "job", cascade = CascadeType.ALL, orphanRemoval = true)
    public List<JobArg> arguments = new ArrayList<>();
    // ... somewhere in Job.java 
    // I used reactive-pgclient so my method return Uni<T>
    public void addArgument(final JobArg jobArg) {
        arguments.add(jobArg);
        jobArg.job = this;
    }
    public static Uni<Job> insert(final UUID userId, final JobDto newJob) {
        final Job job = new Job();
        //... map fields from dto ...
        newJob.getArguments().stream().map(arg -> {
            final JobArg jobArg = new JobArg();
            //... map fields from dto ...
            return jobArg;
        }).forEach(job::addArgument);

        final Uni<Void> jobInsert = job.persist();
        final Uni<UserAction> userActionInsert = UserAction.insertAction(type, job.id, userId, null);
        return Uni.combine().all().unis(jobInsert, userActionInsert).combinedWith(result -> job);
    }

以下是vlad mihalcea博客中的示例代码:对于双向Map:

@Entity(name = "Post")
@Table(name = "post")
public class Post {

    @Id
    @GeneratedValue
    private Long id;

    private String title;

    @OneToMany(
        mappedBy = "post",
        cascade = CascadeType.ALL,
        orphanRemoval = true
    )
    private List<PostComment> comments = new ArrayList<>();

    //Constructors, getters and setters removed for brevity

    public void addComment(PostComment comment) {
        comments.add(comment);
        comment.setPost(this);
    }

    public void removeComment(PostComment comment) {
        comments.remove(comment);
        comment.setPost(null);
    }
}

@Entity(name = "PostComment")
@Table(name = "post_comment")
public class PostComment {

    @Id
    @GeneratedValue
    private Long id;

    private String review;

    @ManyToOne(fetch = FetchType.LAZY)
    private Post post;

    //Constructors, getters and setters removed for brevity

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof PostComment )) return false;
        return id != null && id.equals(((PostComment) o).getId());
    }

    @Override
    public int hashCode() {
        return getClass().hashCode();
    }
}

关于上述Map,有几点需要注意:
@manytoone关联使用fetchtype.lazy,因为否则,我们会退回到对性能不利的急切抓取。
父实体post具有两个实用方法(例如addcomment和removecomment),用于同步双向关联的两侧。当您使用双向关联时,应该始终提供这些方法,否则,您将面临非常微妙的状态传播问题。
子实体postcomment实现equals和hashcode方法。由于等式检查不能依赖于自然标识符,因此需要使用实体标识符代替equals方法。但是,您需要正确地执行此操作,以便在所有实体状态转换中保持一致,这也是hashcode必须是常量值的原因。因为removecomment依赖于equality,所以最好在双向关联中重写子实体的equals和hashcode
.

相关问题