繁体   English   中英

Play Framework 1.x中的模型ID的8位随机值

[英]Random 8 digit value for model id in Play Framework 1.x

我想在play! 1.2.5使用随机的8位数字ID作为model play! 1.2.5 play! 1.2.5代替auto_increment值,并且也没有创建random value ,而是由我自己将其分配给id。 我不知道有没有可能。 我真的用谷歌搜索,但找不到任何东西。

对于下面的答案。 这是我在项目中需要的。 假设我有一个具有2 attr的用户对象。 名和姓。 通过创建该对象,JPA会为该对象的id分配一个auto_inc值。

@Entity
public class User extends Model{
    public String name;
    public String surname;
}

在这里,我的控制器中有createUser方法。

public static void createUser(String name, String surname){
     User user = new User();
     user.name = name;
     user.surname = surname;
     /* it seems to me that the answer below can be a solution for what i want like that
      * user.id = javaGenereted8digitNumId();
      * But I dont want this. I want it is handled in model class
      * and I guess it can be with JPA GenericModel. am I right?
      */

     user.save();

}

采用:

int ID = (int) (Math.Random()*(99999999-a)+a); //a being the smallest value for the ID

如果要在左侧添加0,请使用:

import java.text.DecimalFormat;

并在您的代码中:

DecimalFormat fmt = new DecimalFormat("00000000");
int ID = Integer.parseInt(fmt.format((int) (Math.Random()*(99999999-a)+a)));

编辑:这是对问题更新的更新。

如果您希望User的模型类每次创建自己的唯一8位ID,我建议您创建一个静态变量,该变量将为创建的所有User对象保存最后一个当前使用的ID。 这样,在创建新用户时,它将简单地创建具有下一个可用ID的新用户,这当然将限制为99999999 ID。 如果要进一步进行此操作,则需要创建一个非常大的静态字符串,其中包含用空格分隔的所有使用的ID,并且每次要添加用户时,都将使用.contains(“检查ID的可用性。 ID“)方法

这是您认为User类应该看起来像的一个示例:

public class User extends Model
{
    public String name, surname;
    public int ID;
    public static int lastID;
    public static String usedIDs;

    public User(String name, String surname) //regular User objects
    {
        this.name = name;
        this.surname = surname;
        ID = ++lastID;
        usedID's += ID + " ";
    }

    public User(String name, String surname, int n) //first User object created
    {
        this.name = name;
        this.surname = surname;
        ID = 1;
        lastID = 1;
        usedID's = ID + " ";
    }

//rest of your methods

暂无
暂无

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

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