Search code examples
javaspringjpaentitymanager

java.util.Collections.swap(List<?> list, int i, int j) do nothing


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?


Solution

  • 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.