0

I have a Java Spring MVC and one of my models is Category

@Entity
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class Category extends AuditModel {
    @JsonView(DataTablesOutput.View.class)
    String name;
    boolean active;
    @Column(columnDefinition = "TEXT")
    String description;
    @Column(length = 70)
    String metaTitle;
    @Column(length = 160)
    String metaDescription;
    String friendlyUrl;
    @OneToMany
    List<Category> secondaryCategories;
    String image;
    Long position;
}

I try to swap positions of two Categories in the secondaryCategories list with java.util.Collections.swap(List list, int i, int j) but nothing happens, no errors too.

@Override
public ResponseEntity moveCategoryUpOrDown(Long id, Long parentId, String direction) {
    if (id == parentId) {
        return new ResponseEntity<>("Home category cat't be moved",HttpStatus.BAD_REQUEST);
    }
    Category category = categoryRepository.findOne(id);
    Category parent = categoryRepository.findOne(parentId);
    List<Category> secondaryCategories = parent.getSecondaryCategories();
    if (direction.compareTo("up") == 0) {
        if (secondaryCategories.indexOf(category) <= 0)
            return new ResponseEntity<>(HttpStatus.OK);
        int i = secondaryCategories.indexOf(category);
        int j = secondaryCategories.indexOf(category) - 1;
//            Category previous = secondaryCategories.get(j);
        Collections.swap(secondaryCategories, i, j);
//            categoryRepository.saveAndFlush(previous);
//            categoryRepository.saveAndFlush(category);
        categoryRepository.saveAndFlush(parent);
    }
... etc ..

I also tried EntityManager detach the objects before swaping with no success. I made my own swap method but I wasn't able to swap.

How can I swap two Categories in secondaryCategories?

vdruta
  • 77
  • 2
  • 5
  • You did *nothing* with the entities, you save them, and expect them to change... – meskobalazs Aug 01 '16 at 12:28
  • How is that List ordered? If you don't put `@OrderBy` or `@OrderColumn` then the ordering is by the id of the element. So "swapping" will do nothing in terms of what is in the datastore – Neil Stockton Aug 01 '16 at 12:44

1 Answers1

0

You need to update their position fields, or whatever that sets the ordering of the entity. Changing the order of the collection means nothing from the point of view of the ORM.

meskobalazs
  • 15,741
  • 2
  • 40
  • 63
  • I updated the position fields but inside the secondaryCategories the order is not changed and my secondary categories are listed same as before because of that. – vdruta Aug 01 '16 at 12:50
  • You can add `@OrderBy` on your entity. It should do it – meskobalazs Aug 01 '16 at 12:51