Generating unique ID in a Java class [duplicate] - java

This question already has answers here:
Create a GUID in Java
(7 answers)
Closed 5 years ago.
I am less acquainted with front end and am just a beginner in back end. I am creating a webpage using servlets that reads data of a person from the database and displays it on the page in a form of a list. Each row of the list, consists of a button to contact. When clicked on the button, a message is sent to the person whose data has been selected. My question is- how do we create a unique id from the button click to generate a message id in the message table of the database awaiting a response from the selected person?

All decent databases provide a way to generate unique IDs. A common way is through the usage of sequences, but it can even be simpler, PostgreSQL for example provides the SERIAL and BIGSERIAL types that automatically create a new id for each inserted row.
Long story made short: if you only need a different id for each row, use the equivalent of SERIAL provided by your database, and if you need greater control directly use a SEQUENCE (or its equivalent).

Use UUID Generator
Starting with Java 5, the UUID class provides a simple means for generating unique ids. The identifiers generated by UUID are actually universally unique identifiers.
Example
import java.util.UUID;
public class GenerateUUID {
public static final void main(String... aArgs){
//generate random UUIDs
UUID idOne = UUID.randomUUID();
UUID idTwo = UUID.randomUUID();
log("UUID One: " + idOne);
log("UUID Two: " + idTwo);
}
private static void log(Object aObject){
System.out.println( String.valueOf(aObject) );
}
}
Example run:
>java -cp . GenerateUUID
UUID One: 067e6162-3b6f-4ae2-a171-2470b63dff00
UUID Two: 54947df8-0e9e-4471-a2f9-9af509fb5889
Please refer : http://www.javapractices.com/topic/TopicAction.do?Id=56
I hope this will help.

Related

How to get an entity-related object correctly

I have approximately the following entity:
public class Article {
private String name;
private Long fileId;
}
As you can see, it has a field fileld that contains the id of the associated file, which is also an entity. However, the file does not know anything about the Article, so the only thing that connects them is the fileId field in the Article. Therefore, they must be explicitly linked so as not to get lost. Now to get a linked file, I have to make a separate query to the database for each Article. That is, if I want to get a list of 10 Articles, I need to make a request to the database 10 times and get the file by its id. This looks very inefficient. How can this be done better? I use jooq, so I can't use JPA, so I can't substitute a file object instead of the fileId field. Any ideas?
I'm going to make an assumption that your underlying tables are something like this:
create table file (
id bigint primary key
content blob
);
create table article (
name text,
file_id bigint references file
);
In case of which you can fetch all 10 files into memory using a single query like this:
Result<?> result =
ctx.select()
.from(ARTICLE)
.join(FILE).on(ARTICLE.FILE_ID.eq(FILE.ID))
.fetch();

App crashed after inserting duplicate values for composite key in room db in Android

I make a composite key of two columns when I 1st time the data goes well. But when I insert the same data (duplicate) the app crashed.
How to handle the app not to crash after inserting duplicate data? Just give me a toast message "Data available already"
#Entity(tableName = "ChildRegistration",
indices = {#Index(value = {"childName","mobileNumber"}, unique = true)})
public class ChildRegistration {}`
The problem is that unique is set to true therefore you'll have to have confict resolution. The examples I gave below come directly from the official documentation on the links i gave
For example in your dao
#Insert(onConflict = OnConflictStrategy.IGNORE) suspend fun insert(word: Word)
https://developer.android.com/reference/androidx/room/Update#onConflict()
https://codelabs.developers.google.com/codelabs/android-room-with-a-view-kotlin/#4
Or update one that already exist for example
#Update public void updateSong(Song)
https://developer.android.com/reference/androidx/room/Update
Use onConflict = OnCnflictStrategy.IGNORE and make insert method to return long. If insertion returns -1, it means already exists. Otherwise it will return the row number that inserted.

Generate Unique Employee code in String

I am implementing Employee Management System in Java. I want employee code to be auto generated on new employee registration and I should be in predefined format. I don't want to use auto incremented integer key as a employee ID. I am using MySQL Database and JDBC API to connect to MySQL. Please suggest me a solution.
If the length of the ID does not matter just use java.util.UUID to generate a universally unique identifier.
There can be many approaches to generate an employee Id.I am recommending following most commonly used methods.
1) Timestamp Based :- Use UUID from java.util.UUID to generate random ID's based on host and current time.
UUID uuid = UUID.randomUUID();
2) Custom Information Based
If you want an employeeId to be generated using Company Initials/Employee's Personal Information,
Use employee's username and date of birth
Take a namespace identifier(can be your organisation's name)
With the hash of unique identifier and username of employee,
String source = namespace + username + dateofbirth;
byte[] bytes = source.getBytes("UTF-8");
UUID uuid = UUID.nameUUIDFromBytes(bytes);
3) Use Company Initials :
Lets say your company initials are XYZ.Use a random number generator function to generate any 5 or 6 digit number.
Eg. XYZ47899

How to generate a random string for ID/Name of an Entity instead of a number?

I'm working with the low-level datastore API. I've created an entity like this:
Entity entity = new Entity("Error");
entity.setProperty("description", "foo");
In the datastore viewer, I ses this:
Key Write Ops ID/Name description
----------------------------------------------
ahN0c... 4 259 foo
So the ID/Name field will be generated for me automatically since I'm not supplying anything in the Entity constructor. It generates an "ID" instead of a "Name", which is a number rather than an opaque string (like the "Key" value).
Is there a way to have the datastore generate a random "Name" instead of an "ID" for the Entity's "ID/Name" field?
I ask because if I share this ID with third parties, they could start to figure out roughly how many Error instances I have in my system. I'd rather give them an opaque string for the lookup ID, similar to what's in the auto-generated "Key" field. But I don't see a way to do this.
Thanks
For a similar task I used UUID to create a random string.
String uuid = UUID.randomUUID().toString();
You can use com.google.appengine.api.datastore.KeyFactory, combining the answer from #Devolus, it would look like
final Key key = KeyFactory.createKey("Error", UUID.randomUUID().toString());
final Entity e = new Entity(key);
You could even pass around the String representation of your Entitie's key via KeyFactory.keyToString(key) , may be after an encrypting depending on your security needs.

Android and Java Uuid

I want to generate a uuid for my app i tried many things like wifi mac address , getting android id, serial number , creating pseudo uuid from device
android.os.Build properties .
i also came to know that java itself got Uuid creator class
java.util.UUID
by going through several articles and blogs i am little confused about this . i want to know that if two android device are creating uuid using this java class(java.util.UUID) will that be unique or is there any chance for duplication?
Also in some devices i was not able to find serial number using android.os.Build.SERIAL . is there alternative way to get serial number of device
Assuming you're using the java.util.UUID's randomUUID() function there's a theoretical chance of duplication, but it's incredibly remote. The ids generated are RFC4122 version-4 ids, which have 122 bits randomly set. That means there are 5.32 x 10^^36 possible values. For some perspective on that, if you had a billion devices, each generating a billion IDs per second, it would take roughly 168 billion years for them to finish (~10X the age of the universe).
So, yes, duplication is possible, but (assuming Java is using a high quality random number generator), the odds of it actually happening are so remote as to be meaningless.
to Get Device ID Use Telephoney U can use it here is it is
public static String deviceUDID(Context ctx) {
final TelephonyManager tm = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE);
final String tmDevice, tmSerial, androidId;
tmDevice = "" + tm.getDeviceId();
tmSerial = "" + tm.getSimSerialNumber();
androidId = "" +android.provider.Settings.Secure.getString(ctx.getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
UUID deviceUuid = new UUID(androidId.hashCode(), ((long)tmDevice.hashCode() << 32) | tmSerial.hashCode());
String deviceId = deviceUuid.toString();
Log.d("Device Id", deviceId);
return deviceId;
}

Categories

Resources