有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在使用SpringDataJPA的许多关系中,所有者/子JSON数据的良好模式是什么?

我是春天的新手,我正在努力学习它,和冬眠一起

我有一种情况,我把UsersTasks作为实体,它们之间有很多关系。我已经能够在Spring中使用以下类实现这一点

public class User {
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private long id;

  private String name;

  @Column(name = "username", unique = true, nullable = false)
  private String username;

  private String profile_url;
  private String email;

  @JsonIgnore
  @ManyToMany(cascade = CascadeType.ALL)
  @JoinTable(
    name = "user_tasks",
    joinColumns = {
      @JoinColumn(name = "user_id")
    },
    inverseJoinColumns = {
      @JoinColumn(name = "task_id")
    }
  )
  private Set<Task> tasks = new HashSet<>();
}

public class Task {
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private long id;

  private String title;
  private String description;

  private double storyPoints;

  @CreationTimestamp
  private Instant creationTimestamp;

  @UpdateTimestamp
  private Instant updateTimestamp;

  @ManyToMany(mappedBy = "tasks", cascade = CascadeType.ALL)
  private Set<User> users = new HashSet<>();
}

我已经尝试了很多方法,但我似乎无法理解如何将users插入到我的Controller中的taskjson中。当我POST/api/users/时,我应该能够使用这种JSON格式

{
    "name": "Hardworking Employee",
    "username": "employee",
    "email": "employee@company.com",
    "profile_url": "https://profile.pic",
}

这是完美的。当我POSTapi/tasks/时,理想情况下,我希望按照这些思路发送一些东西

{
    "title": "Do this also",
    "description": "Let's try to do this now",
    "storyPoints": 1.25,
    "users": [
        "employee"
    ]
}

其中users键映射到usernames的数组,或者可能映射到ids的数组。但是,这不会正确注册,Jackson很可能期望数组为Users,并且没有只包含一个StringUser构造函数。但即使有,也无法找到正确的用户,因为必须在model级别创建此构造函数

总的来说,我想知道处理这个问题的好模式是什么?我应该在控制器上添加额外的逻辑吗?有谁能指引我走上正义之路


共 (0) 个答案