简体   繁体   中英

JPA Composite Key part join

I have an existing database schema and I try to make one to many relationship in JPA when PK is a composite of multiple fields and just one of them is FK in the other entity:

DemandId : PK class that consist of two fields

@Embeddable
public class DemandId implements Serializable {

@Column(name = "\"ORDER\"", nullable = false)
private String order;

@Column(name = "SNRP", nullable = false)
private String number;
}

DemandEntity : The entity itself

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

@EmbeddedId
private DemandId id;

@OneToMany(fetch = EAGER, cascade = ALL, mappedBy = "demand")
private Set<PartEntity> parts = new HashSet<>();
}

PartEntity :

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

@Column(name = "SNRP")
private String number;

@ManyToOne
@JoinColumn(name = "SNRP", referencedColumnName = "SNRP", insertable = false, updatable = false)
private DemandEntity demand;
}

This approach leads to an exception:

Exception Description: The @JoinColumns on the annotated element [field demand] from the entity class [class PartEntity] is incomplete. When the source entity class uses a composite primary key, a @JoinColumn must be specified for each join column using the @JoinColumns. Both the name and the referencedColumnName elements must be specified in each such @JoinColumn.

Unfortunatelly I cannot add another join column

@JoinColumn(name = "\"ORDER\"", referencedColumnName = "\"ORDER\"", insertable = false, updatable = false)

Because the PART table doesn't contain the ORDER field and the structure of the database cannot be changed.

Is there a way to perform such mapping?

Regards

If you have composite primary keys and you want to have one to many mapping, I would suggest rather than keeping those keys as composite primary keys, make them composite unique keys.

And make a auto-generated sequence as a primary key.

It is better and more convenient. By the way its my personnel opinion.

I even don't know, if that is possible or not which you are trying to do.

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