I need to make a one-to-many sequence as follows:
for example:
| category | sub category |
|---|---|
| 1 | 1 |
| 1 | 2 |
| 2 | 1 |
| 2 | 2 |
| 2 | 3 |
| 3 | 1 |
Data model:
Java code/Mapping:
Category class
package br.com.bank.adapter.repository.entity;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.Set;
@Entity
@Getter
@Setter
@Table(name = "category")
public class CategoryEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name", nullable = false)
private String name;
@Column(name = "update_at")
private LocalDateTime update;
@OneToMany(mappedBy = "category", orphanRemoval = true, cascade = CascadeType.ALL)
private Set<SubCategoryEntity> subCategoryEntity = new HashSet<>();
}
SubCategory class
package br.com.bank.adapter.repository.entity;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
import java.time.LocalDateTime;
@Entity
@Getter
@Setter
@Table(name = "sub_category")
public class SubCategoryEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name", nullable = false)
private String name;
@Column(name = "update_at")
private LocalDateTime update;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "category_id", nullable = false)
private CategoryEntity category;
}
With the code above, I'm getting the following result:
| category | sub category |
|---|---|
| 1 | 1 |
| 1 | 2 |
| 2 | 3 |
| 2 | 4 |
| 2 | 5 |
| 3 | 6 |