【问题标题】:java.util.Collections.swap(List<?> list, int i, int j) do nothingjava.util.Collections.swap(List<?> list, int i, int j) 什么都不做
【发布时间】:2016-08-01 12:26:13
【问题描述】:

我有一个 Java Spring MVC,我的模型之一是 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;
}

我尝试用 java.util.Collections.swap(List list, int i, int j) 交换 secondaryCategories 列表中两个类别的位置,但没有任何反应,也没有错误。

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

我还尝试了 EntityManager 在交换之前分离对象,但没有成功。我制作了自己的交换方法,但无法交换。

如何交换 secondaryCategories 中的两个类别?

【问题讨论】:

  • 你对实体做了什么,你保存它们,并期望它们改变......
  • List 是如何排序的?如果您不输入@OrderBy@OrderColumn,则排序是按元素的id。因此,就数据存储中的内容而言,“交换”将无济于事

标签: java spring jpa entitymanager


【解决方案1】:

您需要更新他们的position 字段,或设置实体排序的任何内容。从 ORM 的角度来看,更改集合的顺序没有任何意义。

【讨论】:

  • 我更新了位置字段,但在 secondaryCategories 中的顺序没有改变,因此我的次要类别与以前一样列出。
  • 您可以在您的实体上添加@OrderBy。它应该这样做
猜你喜欢
  • 1970-01-01
  • 2011-07-01
  • 1970-01-01
  • 2015-06-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多