我有一個Java Spring MVC和我的車型之一是java.util.Collections.swap(名單<?>名單,INT I,詮釋J)什麼都不做
類別@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中交換兩個類別?
你沒有*與實體*,你保存它們,並期望它們改變...... – meskobalazs
該列表是如何排序的?如果您不放置'@ OrderBy'或'@ OrderColumn',那麼順序就是元素的id。因此,「交換」在數據存儲區 –