【问题标题】:Add entity with OneToOne Relation using JPA and REST使用 JPA 和 REST 添加具有 OneToOne 关系的实体
【发布时间】:2015-08-24 09:53:19
【问题描述】:

我正在使用 Spring JPA Restful,但我不明白如何插入带有外键的实体。

活动实体:

@Entity
@Table(name= "Activity")
public class Activity implements Serializable{

   @Id
   @GeneratedValue(generator = "uuid")
   @GenericGenerator(name="uuid", strategy = "uuid2")
   @Column(name = "uuid", nullable = false, unique = true)
   private UUID uuid;

   @OneToOne(fetch = FetchType.EAGER, cascade=CascadeType.MERGE)
   @JoinColumn(name="type", nullable = false)
   private ActivityType type;

   @Column(nullable = false)
   private String label;

ActivityType 实体:

@Entity
@Table(name= "ActivityType")
public class ActivityType implements Serializable {

   @Id
   @GeneratedValue(strategy = GenerationType.AUTO)
   private long id;

   @Column(nullable = false, unique = true)
   private String code;

   @Column(nullable = false
   private String label;

是否可以简单地插入活动?像这样的 JSON 存在 ActivityType 的 id “1”:

创建活动: {"label":"LABEL","type":1}

使用这段代码我必须这样做:

创建活动: {"label":"LABEL","type":{"id":1}}

返回值是:

{
 "uuid": "a54b27aa-8d49-41fd-8976-70c019c40e3b",
 "type": {
   "id": 1,
   "code": null,
   "label": null
 },
 "label": "LABEL",
 "details": null
}

【问题讨论】:

    标签: spring hibernate jpa


    【解决方案1】:

    我使用库 gson 将域类解析为 JSON。

    //... 用于制作活动的代码,假设您有一个 Activity 对象 myActivity

    只需在要将对象解析为 JSON 的位置添加以下代码即可。

    Gson gson = new GSON();
    String json = gson.toJson(myActivity);
    

    【讨论】:

      猜你喜欢
      • 2021-05-22
      • 1970-01-01
      • 2019-07-26
      • 1970-01-01
      • 2019-01-07
      • 2012-01-06
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      相关资源
      最近更新 更多