Junior — Middle
Can one part of a composite primary key have a null value?
sobes.tech AI
Answer from AI
In a composite primary key in a database, none of the parts can have a null value. This is because the primary key must uniquely identify a record, and null indicates the absence of a value, which violates data uniqueness and integrity.
In Java, if you use a composite key, for example in JPA, all fields that are part of the composite key must not be null.
Example of a composite key in JPA:
@Embeddable
public class OrderItemId implements Serializable {
private Long orderId;
private Long productId;
// getters, setters, equals, and hashCode
}
@Entity
public class OrderItem {
@EmbeddedId
private OrderItemId id;
// other fields
}
The values of orderId and productId must be filled and cannot be null.