如何确保我使用Spring JPA按正确顺序插入SQL数据?

huangapple go评论82阅读模式
英文:

How do I make sure that I insert SQL data in right order with Spring JPA?

问题

当我插入:

data1
data2
data3
data4
data5
..
..
..
dataN

使用以下代码将数据插入到MySQL数据库:

DataLogg dataLogg = new DataLogg(0, time, DO0, DO1, DO2, DO3, AI0, AI1, AI2, AI3, loggerIdValue, samplingTimeValue, pulseNumber, ControlView.selectedBreakPulseLimit, stopSignal, comment);
dataLoggRepository.saveAndFlush(dataLogg);

如果运气不好的话,数据插入的顺序可能是这样的:

data1
data2
data4
data3
dataN
..
..
..
data5

问题:

我如何保证插入行的顺序与读取行的顺序相同?我不希望数据以随机顺序显示。最新的数据需要在顶部,最旧的数据需要在底部。

英文:

When I insert:

data1
data2
data3
data4
data5
..
..
..
dataN

Into a MySQL database with this code:

DataLogg dataLogg = new DataLogg(0, time, DO0, DO1, DO2, DO3, AI0, AI1, AI2, AI3, loggerIdValue, samplingTimeValue, pulseNumber, ControlView.selectedBreakPulseLimit, stopSignal, comment);
dataLoggRepository.saveAndFlush(dataLogg);

It will insert data like this, if I have bad luck.

data1
data2
data4
data3
dataN
..
..
..
data5

Question:

How can I guarantee that the same order I insert the rows, I can read them as the same order as well? I don't want it in random order. The last data need to be at the top and the first data need to be at the bottom.

答案1

得分: 3

你问:

> 我怎样才能确保我插入行的顺序,我在读取它们时也能保持相同的顺序?

答案是,在 SQL 表中实际上没有内部的“顺序”。当查询时确保特定顺序的方式是在查询中使用 ORDER BY 子句,例如:

SELECT name
FROM yourTable
ORDER BY name;
英文:

You asked:

> How can I guarantee that the same order I insert the rows, I can read them as the same order as well?

The answer is that there is no internal "order" to a SQL table, for all intents and purposes. The way you ensure a certain order when querying is to use an ORDER BY clause with the query, e.g.

SELECT name
FROM yourTable
ORDER BY name;

huangapple
  • 本文由 发表于 2020年10月6日 16:01:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/64221672.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定