简体   繁体   English

用Java生成顺序事务ID

[英]Generating Sequential Transaction ID's in Java

I want to generate Sequential Trnsaction ID's for employees to store in the Database ... I wrote the below jsp code(This ain't the code to insert Tx ID in the database) ..The code works fine .. When i use order by clause to see the latest transaction ..i'm not getting the expected transation ID...How can i make the transaction ID's unique , Sequential so that i can retrieve them in a particular sequence by using Order By clause? 我想为员工生成顺序的Trnsaction ID,以存储在数据库中...我写了下面的jsp代码(这不是在数据库中插入Tx ID的代码)..代码工作正常..当我使用order时by子句以查看最新交易..我没有获得预期的交易ID ...我如何使交易ID唯一,顺序,以便可以使用Order By子句按特定顺序检索它们?

  <%
         String url = "jdbc:mysql://localhost:3306/";

        String dbName = "ystem";
        String driver = "com.mysql.jdbc.Driver";
        String userName = "root";
        String password = "";
        try {
            Class.forName(driver).newInstance();
            Connection conn = DriverManager.getConnection(url+dbName,userName,password);
            Statement stat=conn.createStatement();
            ResultSet rs=stat.executeQuery("select count(*) from `employee`");
            int x=0;
            UUID idOne = UUID.randomUUID();
            while(rs.next()) {                    
                x=Integer.parseInt(rs.getString(1))+1;
            }
            out.println(idOne.toString().toUpperCase()+"-"+String.valueOf(x));
                        stat.close(); conn.close();
        }
        catch(Exception x) {
            out.println(x.getMessage());
        }
    %>

Leaving aside the wisdom of this approach, appending the count to the UUID isn't going to give you something that will be meaningfully orderable by an order by clause because you are creating something in the form RANDOMSTUFF-2 . 抛开这种方法的智慧,将计数添加到UUID不会给您可以通过order by子句有意义地order by因为您正在创建RANDOMSTUFF-2形式的RANDOMSTUFF-2 That can't be ordered in any sequence because order by will sort a string column lexically starting with the first character. 不能以任何顺序进行排序,因为order by将以字符串形式对从第一个字符开始的字符串列进行排序。

So instead, put the counter at the beginning of your string. 因此,将计数器放在字符串的开头 Then you'll have something order by can meaningfully sort: 然后你就会有一些order by可以有意识排序:

String s = String.valueOf(x) + "-" + idOne.toString().toUpperCase();

(Though you'll probably want/need to zero-pad the output of String.valueOf(x) because otherwise "1000" will be sorted to be before "2" . So you need "2" to output as "0002" , for example.) (尽管您可能希望/需要对String.valueOf(x)的输出进行零填充,因为否则, "1000"将被排序为在"2"之前。因此,您需要将"2"输出为"0002" ,例如。)

(and of course you should use StringBuilder.append() (or StringBuffer if your version of Java is old enough) rather than string concatenation). (当然,你应该使用StringBuilder.append()StringBuffer ,如果你的Java版本是够大),而不是字符串连接)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM