0


I want to display on my jsp something like this

CategoryParent1
-----Subcategory1
-----Subcategory2
CategoryParent2
-----Subcategory1
-----Subcategory2

In which way i can solve it? Does spring-mvc has some library for it? Or i must use some external libraries?

I have a Category model

@Entity
public class Category {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
@ManyToOne
private Category parentCategory;
@OneToMany(mappedBy = "parentCategory", cascade = CascadeType.ALL)
private List<Category> childCategories = new ArrayList<>();

public Category() {
}

public Category(String name){
    this.name = name;
}

public Category(String name, Category parentCategory) {
    this.name = name;
    this.parentCategory = parentCategory;
}

public Integer getId() {
    return id;
}

public void setId(Integer id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public Category getParentCategory() {
    return parentCategory;
}

public void setParentCategory(Category parentCategory) {
    this.parentCategory = parentCategory;
}

public List<Category> getChildCategories() {
    return childCategories;
}

public void setChildCategories(List<Category> childCategories) {
    this.childCategories = childCategories;
}
}

1 Answers1

1

I have done the similar task but with recursive query. Here is the link

If you don't want to use recursive query. here is what you need to do.

  • Eagerly fetch child categories (see hibernate eager fetch| lazy load)
  • Remove the "sub query" which is inside the "main query" and remove the recursing statement of a function
  • If you have successfully created relationship, you can just get its children categories by using your "getchildrencategories" method.
  • It is your choice whether you use recursive function or not.

And do not use List its better to use Set:

@OneToMany(fetch = FetchType.EAGER, mappedBy="parentCategory", cascade=CascadeType.REMOVE, orphanRemoval=true )
private Set<Categories> childCategories = new HashSet<Categories>();
Community
  • 1
  • 1
nikesh adhikari
  • 113
  • 2
  • 11