Use @IdClass (composite key)
Yes, this is possible. This approach can be used when you read from a DB view. The below example demonstrates how to mark all (2, in the given example) columns as the composite ID:
import java.io.Serializable;
import lombok.Data; // auto-generates AllArgs contractor, getters/setters, equals, and hashcode
@Data
@Entity
@IdClass(MyEntity.class) // <--this is the extra annotation to add
@Table(name = "my_table")
public class MyEntity implements Serializable{ // <--this is the extra interface to add
@Id // annotate each column with @Id
private String column1;
@Id // annotate each column with @Id
private String column2;
}
- The above MyEntity uses the full record state as the key:
- --so, in addition to @EqualsAndHashcode, do flag the class with Serializable interface;
- --annotate each field with @ID
- In your <T, ID> repository say the ID is your full (entity) class:
interface MyEntityRepo extends CrudRepository<MyEntity, MyEntity> {
// ^^^the full record is the ID
See also:
- docs.oracle.com - Example 7.4-7.5: Non-Embedded Composite Primary Key
- baeldung.com/jpa-composite-primary-keys, for more fine-grained custom IdClass, with fewer (than all) columns in the ID.