【问题标题】:Problem to implement bidirectional relationship in hibernate with my spring boot api使用我的 spring boot api 在休眠中实现双向关系的问题
【发布时间】:2023-01-10 06:32:52
【问题描述】:

我想用这个规范创建一个 spring boot rest 控制器:

电力和天然气供应公司的客户可以选择通过电子邮件或普通邮件接收他们的月度账单,也可以选择两者都不接收。

我的目标是创建 java hibernate 实体来管理这些客户和他们发送账单的选择。

公用事业客户由他们的电子邮件标识,并且可以有多个选择更改事件来更改客户的选择状态。

客户做出的每个选择都会生成一个选择更改事件。

选择更改事件与客户相关。客户可以有多个选择事件。

这是我的 java 实体。

@Entity
@Table(name = "customers")
public class Customer {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Email(message="this field must respect the email format !")
    private String email;
    
    @ManyToOne
    private Choices choices;

}


@Entity
@Table(name = "choices")
public class Choices {

    @Id
    private String id;

    @Column(name = "email")
    private boolean isThisChoice;
    
    @OneToOne
    private Customer customer;

}

The resulting customer with id 24587 (GET request):
{
  "id": "24587",
  "email": "tartampion",
  "choices": [
    {
      "id": "regular mail",
      "isThisChoice": false
    },
    {
      "id": "email",
      "isThisChoice": true
    }
  ]
}

我必须有客户选择的事件管理实体吗

【问题讨论】:

  • 您的模型没有意义:您有一个单一的“选择”属性映射为 ManyToOne - 如此多的客户使用单个“电子邮件”选择实例,但是单个电子邮件选择实例如何引用单个客户?试试看关于如何将数据存储在表中——这可能会帮助您以更适合您的应用程序用例的方式映射实体。

标签: java spring hibernate jpa bidirectional-relation


【解决方案1】:

你的意思是一个模型更像:

@Entity
@Table(name = "customers")
public class Customer {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Email(message="this field must respect the email format !")
    private String email;
    
    @ElementCollection
    @CollectionTable(name="Choices")
    @MapKeyColumn(name="CHOICE") //an "EMAIL" or "MAIL" string. You can use an enum instead if you want, but I wouldn't for upgrade reasons.
    @Column(name="enabled")
    private Map<String, Boolean> choices;

}

这将为您提供一个 Map 的选择,导致 JSON 更像:

{
  "id": "24587",
  "email": "tartampion",
  "choices": {
      "MAIL": false,
      "EMAIL": true
    }
}

如果您将来获得其他选项和组合,它应该更具可扩展性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-31
    • 2021-12-23
    • 2016-09-04
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 2014-08-14
    相关资源
    最近更新 更多