我们拥有的PostgreSQL数据库是常见的多租户数据库。
问题是,需要在" customerNumber"中自动生成一个唯一的号码。列需要按顺序排列。
这里的诀窍是,每个" hotelLocation"的序列必须是唯一的。
以下是表的示例布局,
@Entity
public class CustomerInfo {
@Id
@GeneratedValue(...)
private Long idNumber;
String hotelLocation;
/** Looking for option where, this number needs to
auto generated on SAVE, and need to be in separate sequence
for each hotelLocation **/
private Long customerNumber;
}
所以最后这里是输出的样子,
+----------+---------------+----------------+
| idNumber | hotelLocation | customerNumber |
+----------+---------------+----------------+
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 2 | 1 |
| 4 | 1 | 3 |
| 5 | 2 | 2 |
+----------+---------------+----------------+
我可以通过基于Hibernate或通过触发器生成唯一编号。
搜索,我得到了关注,
Hibernate JPA Sequence (non-Id)
但是这个会按顺序继续生成,而不会为每个" hotelLocation"
分别生成序列。任何解决方案都非常有用。我相信很多人都有多租户数据库寻找类似的解决方案。
由于
答案 0 :(得分:1)
您可以使用postgresql窗口函数row_number()
轻松完成此操作。
不知道您的数据库,但它应该是这样的:
SELECT idNumber, hotelLocation,
row_number() OVER (PARTITION BY hotelLocation ORDER BY idNumber) AS
customerNumber FROM table
在此处查看有关窗口功能的更多信息:Understanding Window Functions