Ebean/DB模拟Oracle序列生成ID

版权声明:版权所有,转载请注明出处。 https://blog.csdn.net/yangzhong0808/article/details/78951943

通过for update给ID表加一把锁,保证数据的一致性

public static Long genSeqId() {

    Long newId = 0L;
    String sql = "select seq_value from seq_table where seq_name = 'tbs_meminfo_id' for update";
    EbeanServer server = Ebean.getServer("rds");
    try {
        server.beginTransaction();

        SqlRow row = server.createSqlQuery(sql).findUnique();
        Long oldId = row.getLong("seq_value");

        sql = "update seq_table set seq_value = " + (oldId + 1) + " where seq_value = " + oldId + " and seq_name = 'tbs_meminfo_id'";
        int result = server.createSqlUpdate(sql).execute();
        if (result > 0) {
            newId = oldId + 1;
        }
    } catch (Exception e) {
        e.printStackTrace();
        newId = -1L;
    } finally {
        server.commitTransaction();
    }
    return newId;
}

没有更多推荐了,返回首页