Jls
Jls

Reputation: 74

Spring Boot: How to create an Entity with a composite key

I was creating my classes for a project using a chart for practice purposes until I stumbled upon this order_items:

part of the chart I'm using

I had no problem creating an Entity like Orders or Products because I knew that for Orders I just had to do something like:

@Entity
@Table(name = "orders")
public class Orders {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "order_id")
    private Integer orderId;
    // rest of the code...
}

And for for Products something like:

@Entity
@Table(name = "products")
public class Products {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "product_id")
    private Integer productId;
    // rest of the code...
}

But the table order_items has the variables order_id and item_id, does that count as a composite key? If that is the case, how should those variables look in my OrderItems class?

@Entity
@Table(name = "order_items")
public class OrderItems {
    
    @Column(name = "order_id")
    private Integer orderId;
    @Column(name = "item_id")
    private Integer itemId;
    // rest of the code...
}

I've checked different questions and they mention using @IdClass or @EmbeddableId for composite keys, but I'd like to confirm first if that is what I should do in this situation, unless it's not the case, maybe there are more approaches.

I'd really appreciate opinions and/or any article related to this, thank your for your time.

Upvotes: 1

Views: 1364

Answers (1)

I_AM__PAUL
I_AM__PAUL

Reputation: 138

As you mentioned you can use @EmbeddableId.

Here is example :

@Embeddable
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder(toBuilder = true)
public class OrderItemsPK  implements Serializable {
private static final long serialVersionUID = 1L;

    @Column(insertable = false, unique = false, updatable = false, nullable = false,name = "order_id")
    private Long orderId;

    @Column(insertable = false, unique = false, updatable = false, nullable = false,name = "products_id")
    private Long productsId;
}

And the Order Items Class.

@Entity
public class OrderItems {

    @EmbeddedId
    private OrderItemsPK id;

    @OneToOne
    @JoinColumn(name = "products_id", nullable = false, unique = false, insertable = false, updatable = false, referencedColumnName = "products_id")
    private Products products;

    @OneToOne
    @JoinColumn(name = "orders_id", nullable = false, unique = false, insertable = false, updatable = false, referencedColumnName = "orders_id")
    private Order order;

    private Long itemId;
}

Upvotes: 1

Related Questions