'Spring Data JPA ONLY FOR PROFESSIONALS
My goal is to create multiple entities (Subbox) from a single entity (Box), just like Matryoshka dolls. To abstract what we are addressing here, consider the following scenario:
First we have an entity "Box":
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity
@ToString
@Table(name="box")
public class Box {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "idbox", updatable = false, nullable = false)
private int idbox;
@Column(name = "brand")
private String brand;
@Column(name = "size")
private BigDecimal size;
@OneToMany
private Set<Subbox> subbox;
@OneToMany
private Set<Content> content;
}
and another entity Subbox:
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity
@ToString
@Table(name="subbox")
public class Subbox {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "idsubbox", updatable = false, nullable = false)
private int idsubbox;
@Column(name = "brand")
private String brand;
@Column(name = "size")
private BigDecimal size;
@ManyToOne
@JoinColumn
private Box box;
@OneToMany
private Set<Content> content;
}
If we query from Subbox, we should get something similar to that:
+----------+-------+------+-------------------+-----------+
| idsubbox | brand | size | content_idcontent | box_idbox |
+----------+-------+------+-------------------+-----------+
1 Abcd 5.0 1 13
2 Abcd 5.0 1 13
3 Abcd 5.0 1 13
So we have 3 different subboxes(1, 2, 3) of the same box(13). The problem is that with the configuration above it's not possible to keep creating subboxes inside a subbox, we would have to create a Subsubbox entity, Subsubsubbox and so on.
The question is, how can I create a Box inside a Box infinitely without having to create N entities? An inner box (the box inside a top box) should have the very same properties from the top box, but its values could differ, just like the dolls have different sizes.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
