如何坚持使用Hibernate

时间:2017-06-05 11:36:08

标签: java hibernate

我有一个名为“Token Requestor”和“Certificates”的类。每个令牌请求者都有许多证书,证书只有只有一个令牌请求者。

TokenRequestor.java

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

    @Id
    @SequenceGenerator(name = "TOKEN_REQUESTOR_ID_GENERATOR", sequenceName = "TOKEN_REQUESTOR_ID")
    @GeneratedValue(strategy = GenerationType.AUTO, generator = "TOKEN_REQUESTOR_ID_GENERATOR")
    @Column(name = "TOKEN_REQUESTOR_ID")
    private Long id;
    @OneToMany(mappedBy = "tokenRequestorId")
    private List<Certificate> certificates;

Certificate.java

@Entity
@Table(name = "CERTIFICATES")
public class Certificate {

    @Id
    @SequenceGenerator(name = "CERTIFICATES_ID_GENERATOR", sequenceName = "SQ_CERTIFICATES_ID")
    @GeneratedValue(strategy = GenerationType.AUTO, generator = "CERTIFICATES_ID_GENERATOR")
    @Column(name = "CERTIFICATES_ID")
    private Long id;
    @ManyToOne(fetch = FetchType.EAGER,cascade = CascadeType.ALL)
    @JoinColumn(name = "TOKEN_REQUESTOR_ID")
    private TokenRequestor tokenRequestorId;    //Foreign key*/

当我插入令牌请求者时,必须创建证书。它们已创建,但证书表中的TOKEN_REQUESTOR_ID为null。为什么会这样?

POST令牌请求者

{
    "domain": "GTW",
    ...,
    "certificates": [
    {
      "usage": "ENC",
      "alias": "encryption_cert",
      "content": "-----BEGIN CERTIFICATE----- ... -----END CERTIFICATE-----"
    },
    {
      "usage": "DEC",
      "alias": "decryption_cert",
      "content": "-----BEGIN CERTIFICATE----- ... -----END CERTIFICATE-----"
    },
    {
      "usage": "SSL",
      "alias": "communication_cert",
      "content": "-----BEGIN CERTIFICATE----- ... -----END CERTIFICATE-----"
    },
    {
      "usage": "CA",
      "alias": "TSP ROOT CA",
      "content": "-----BEGIN CERTIFICATE----- ... -----END CERTIFICATE-----"
    }
  ]
}

1 个答案:

答案 0 :(得分:1)

你的问题是你将关系定义为双向关系,这基本上意味着关系的每一方都应该引用另一方。

假设我们有TokenRequestor对象,这个对象有两个证书,只有当关系是单向的时候(你可以将你的关系转为解决这个问题)这个就足够了,对于双向关系你需要有一个持有对TokenReguestor的引用的证书。