I have a many-to-many relationship between a Category
and an Attribute
object since every category can have many attributes.
This is my Category
object:
@Data
@Entity
@Table(name = "categories")
public class Category {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "category_id")
private Long id;
@Column(nullable = false)
private String name;
@Column(name = "image_name", columnDefinition = "VARCHAR(255)")
private String imageName;
@Column(nullable = false)
private Integer level;
@OneToMany(mappedBy = "category")
private List<Listing> listings;
@OneToMany(mappedBy = "parentCategory", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<Category> subcategories;
@ManyToOne
@JoinColumn(name = "parent_category_id")
private Category parentCategory;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(
name = "categories_attributes",
joinColumns = @JoinColumn(name = "category_id"),
inverseJoinColumns = @JoinColumn(name = "attribute_id")
)
private Set<Attribute> attributes;
}
and this is the Attribute
object:
@Data
@Entity
@Table(name = "attributes")
public class Attribute {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "attribute_id")
private Long id;
@Column
private String name;
@OneToMany(mappedBy = "attribute")
private List<ListingDetail> listingDetails;
@OneToMany(mappedBy = "attribute", cascade = CascadeType.ALL)
private List<AttributeValue> attributeValues;
@ManyToMany(mappedBy = "attributes")
private Set<Category> categories;
}
When I try to fetch a category object from the database, the attributes
field is always empty, even though it has valid records. The categories_attributes
table looks like this:
category_id | attribute_id
19 1
19 2
19 4
19 8
I have a service layer, in which I map the Category
object to a DAO response and before the mapping, the set is empty as well, so the problem isn’t from the mapping process.
This is the Category
JSON response:
"id": 19,
"name": "Cars and Jeeps",
"imageName": null,
"level": 2,
"subcategories": [
"id": 119,
"name": "Acura",
"imageName": null,
"level": 3,
"subcategories": [],
"attributes": []
},
{
"id": 120,
"name": "Alfa romeo",
"imageName": null,
"level": 3,
"subcategories": [],
"attributes": []
},
],
"attributes": []
What am I missing?