需要ArrayList按保存到数据库的顺序保存对象。使用@OrderColumn可以实现此目的,但是由于某种原因,它未能按首尾排序。
以下测试将保存2个对象,并尝试按降序检索对象(请参阅最后一行),
Watching.class
@ManyToMany(cascade = CascadeType.ALL,
targetEntity = Ticker.class,
fetch = FetchType.LAZY)
@JoinTable(name="watching_ticker",
joinColumns = @JoinColumn(name="watching_id"),
inverseJoinColumns= @JoinColumn(name="ticker_id"))
@OrderBy("id desc")
private List<Ticker> tickers;
...
Ticker.class
@JsonIgnore
@ManyToMany
@JoinTable(name ="watching_ticker",
joinColumns = @JoinColumn(name ="ticker_id"),
inverseJoinColumns = @JoinColumn(name = "watching_id"))
protected Set<Watching> watchings;
..
Tester
Account account;
AccountService accountService;
Ticker ticker;
Ticker tickerTwo;
@Before
public void setUp() throws Exception {
account = ...
ticker = ...;
tickerTwo = ...;
....
}
@Test
public void testSave() {
Watching watching = account.getWatching();
watching.getTickers().add(ticker);
watching.getTickers().add(tickerTwo);
Watching saved = accountService.save(account).getWatching();
Ticker one = saved.getTickers().get(0);
int size = saved.getTickers().size();
assertEquals(2, size);
Assert.assertEquals(one, tickerTwo); <-- fails
}
答案 0 :(得分:0)
改为使用@OrderBy。 @OrderColumn通过除ID之外的不可见列对记录进行排序。
作为实体状态或状态的一部分,订单列不可见 可嵌入的类。
OrderBy批注应用于显示为 持久状态并由应用程序维护。
https://docs.oracle.com/javaee/6/api/javax/persistence/OrderColumn.html