简体   繁体   中英

How persist with Hibernate

I have a class named "Token Requestor" and "Certificates". Each Token Requestor have many Certificates and Certificates have only one Token Requestor.

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*/

When I insert a Token Requestor, they certificate must be create. They are created but with TOKEN_REQUESTOR_ID null in Certificate table. Why this happens?

POST Token Requestor

{
    "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-----"
    }
  ]
}

your problem is that you define the relationship to be bidirectional, which basically means each side of the relation should have reference to the other side.

lets say we have TokenRequestor object , this object has two Certificates, this would be enough only if the relation is unidirectional ( which you can turn your relation to to solve this issue btw), for a bidirectional relation you need to haveeach one of the Certificate holding a reference to their TokenReguestor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM