Reputation: 639
I would like to use random 8 digit number id for model
in play! 1.2.5
instead of auto_increment
value and also without creating a random value
, assigning it to id by myself. I do not know it is possible or not. I really googled about it but I could not find anything.
for the answer below. Here is what i need in my project. Suppose that i have a user object which has 2 attr. name and surname. With the defult creation of this object, JPA assing a auto_inc value for the id of this object.
@Entity
public class User extends Model{
public String name;
public String surname;
}
And here i have createUser method in my controller.
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();
}
Upvotes: 0
Views: 506
Reputation: 722
use:
int ID = (int) (Math.Random()*(99999999-a)+a); //a being the smallest value for the ID
and if you want to include the 0's on the left, use:
import java.text.DecimalFormat;
and in your code:
DecimalFormat fmt = new DecimalFormat("00000000");
int ID = Integer.parseInt(fmt.format((int) (Math.Random()*(99999999-a)+a)));
EDIT: This is an update to your update of the question.
If you want the model class of User to create its own unique 8digit ID everytime, i suggest you make a static variable that saves the last currently used ID for all User objects created. This way on creation of a new user, it will simply create a new user with the next available ID, this will of course be limited to 99999999 ID's. If you want to go further then this, you will need to create a very large static String containing all the used ID's seperated by spaces, and everytime you want to add a user, it will check for the ID availability by using .contains("ID") method
Here's an example of what your User class should look like i believe:
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
Upvotes: 1