Reputation: 756
I am trying to establish a OneToOne relationship between two entities (PartnerDetails
and JWTData
. How ever, I only want to store the primary key of PartnerDetails
entity in JWTData
, not the whole object, like this.
@Entity
@Data
@Table(name = "partner_details")
public class PartnerDetails {
@Id
@Column(name = "partner_id")
private String partnerId;
@OneToOne(cascade = CascadeType.ALL, mappedBy = "partnerId")
private JWTData jwtData;
}
@Entity
@Data
@Table(name = "jwt_data")
@NoArgsConstructor
public class JWTData {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@OneToOne(targetEntity = PartnerDetails.class)
@JoinColumn(name = "partner_id", foreignKey = @ForeignKey(name = "fk_jwt_partnerdetails_partnerid"))
private String partnerId;
@NotBlank
private String secret;
}
But after fetching the JWTData
using repository, Hibernate cannot convert the String to a PartnerDetails
. Can this be done using any other way?
Upvotes: 0
Views: 364
Reputation: 11561
If you just add PartnerDetails
to JWTData
then JPA will know to use only the id. JPA is an Object Oriented framework so you should reference objects unless you specifically want a field. JPA handles the details for you. Note that in this configuration JWTData
in the "owning" entity because of the mappedBy
annotation, therefore only setting the partnerDetails
field in a JWTData
instance will persist the relationship to the database. The jwtData
field in PartnerDetails
is for query results only and makes for a Bidirectional
instead of a Unidirectional
mapping. Also, because of this, having a CascadeType
setting generally only makes sense on the owning entity since it is the one handling the database updates and deletes.
When playing around with JPA be sure to turn on the SQL output so that you know what is actually happening.
@Entity
@Data
@Table(name = "partner_details")
public class PartnerDetails {
@Id
@Column(name = "partner_id")
private String partnerId;
@OneToOne(mappedBy = "partnerDetails")
private JWTData jwtData;
@Entity
@Data
@Table(name = "jwt_data")
@NoArgsConstructor
public class JWTData {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
// even though it looks like the entire class it's only saving the id to the database.
@OneToOne
private PartnerDetails partnerDetails;
Upvotes: 1