[英]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.