how to retrieve ID after object store into database - java

I am using Java, spring, jpa for our application. I want to retrieve Id of insert row. Basically our ID is generated at the time of storing object into database.
RoleRequest role = new RoleRequest();
roleRequest.setUser(user);
roleRequest.setRole(role);
roleRequest.setRequestDate(new Date());
roleRequest.setStatusCode(Enum.PENDING);
Dao.persist(roleRequest);
So after storing this object, I need new generated id for this object, so that will perform some operation on it.

Dao.persist(roleRequest);
After this line, the id should be set, so you can just do
Long id = roleRequest.getId();
(assuming id as id column and Long as id type)

What about:
oleRequest role = new RoleRequest();
roleRequest.setUser(user);
roleRequest.setRole(role);
roleRequest.setRequestDate(new Date());
roleRequest.setStatusCode(RoleRequestStatusEnum.PENDING);
Dao.persist(roleRequest);
int myId = roleRequest.getId();
You may need to do EntityManager.flush() after EntityManager.persist() (YMMV).

Related

Finding random (auto) id assigned to our document by Firestore

I know its a bit weird question but how can I access the unique (auto) id google firebase generates for my document whenever I create new document. For example this is my code
val postCollections = db.collection("posts")
val newPost = Post(text, user, currentTime)
postCollections.document().set(newPost)
How can I know that what is the id generated for this document of "newPost" because i want to use that id in my code and at the same time i dont want to send custom id because it won't be unique
val postCollections = db.collection("posts")
val newPost = Post(text, user, currentTime)
postCollections.document().set(newPost)
As you've likely discovered, .set() returns a Promise <void> .
But what you've ignored is .set() only operates on a DocumentReference - which is what you get from postCollections.document(). A DocumentReference has properties id and path - it is the .document() that creates a new, unique, documentId.
So:
val postCollections = db.collection("posts")
val newPost = Post(text, user, currentTime)
val newRef = postCollections.document()
newRef.set(newPost)
And now you have the document id (and path) available as properties of newRef.
https://firebase.google.com/docs/reference/js/firebase.firestore.DocumentReference

Copying Google Gloud Datastore entities from one namespace to an other

I'm copying Google Cloud Datastore entities from one namespace to an other with java like this:
Key newKey = Key.newBuilder(oldEntity.getKey()).setNamespace(NEW_NAMESPACE).build();
datastore.put(Entity.newBuilder(oldEntity).setKey(newKey).build());
Since the entities have numerid id's generated by Datastore and the id's of the copied entities need to remain the same I need to also let Datastore know to allocate these id's, for that I'm using DatastoreService.allocateIdRange
But this is giving me an error:
Exceeded maximum allocated IDs
Does this mean that there is no way to achieve what I'm trying to achieve?
EDIT 1
The code that allocates the ids:
#POST
public void post(
#QueryParam("namespace") String namespace,
#QueryParam("kind") String kind,
#QueryParam("id") long id,
#QueryParam("parentKind") String parentKind,
#QueryParam("parentName") String parentName,
#QueryParam("parentId") Long parentId
) {
NamespaceManager.set(namespace);
DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
Key parent = null;
if (parentKind != null) {
if (parentName != null)
parent = KeyFactory.createKey(parentKind, parentName);
else
parent = KeyFactory.createKey(parentKind, parentId);
}
ds.allocateIdRange(new KeyRange(parent, kind, id, id));
}
I think you can skip the key creation. This is my code for updating namespaces:
GoogleCloudDatastore gds = new GoogleCloudDatastore();
Datastore ds = gds.getCredentials();
final KeyFactory keyFactory = ds.newKeyFactory().setKind(entityKind).setNamespace(NAME_SPACE);
Key newKey = ds.allocateId(oldEntity.getKey);
Entity newEntity= Entity.newBuilder(newKey).set("someParameterName", someParameterValue).build();
Hope this helps.
Here is an answer provided on Google's Issue Tracker:
allocateIdRange only works with Sequential contiguous IDs and not Scattered IDs which are above the Sequential ID range.
As explained in the 'Best Practices' documentation, if need be it is recommended to send an 'allocateIds' request to Datastore to find and allocate a contiguous range of unique IDs and use those to save entities to, instead of saving entities to the Datastore first which are auto-assigned Scattered IDs and cannot be allocated with allocateIdRange.

Cannot get custom document ID in Couchbase Lite - Android

I'm new in Couchbase Android. I use Couchbase Lite v1.1.0 to save my data local. But I facing with some problems when to do that. I googled, read document in Couchbase Lite and find all post in stackoverflow but I still not understand what I facing.
Here is my snippet demo code to save my data in database with custom id of document is index i:
cbManager=new Manager(new AndroidContext(context),
Manager.DEFAULT_OPTIONS);
cbDatabase=cbManager.getDatabase("my_db");
.....
for(int i=0; i<10; i++){
Document document=cbDatabase.getDocument(String.valueOf(i)); // This line I custom document with id i
Map<String,Object> docContent= new HashMap<String, Object>();
docContent.put("title", title);
docContent.put("firstName", firstName);
docContent.put("lastName", lastName);
try{
document.putProperties(docContent);
} catch (CouchbaseLiteException e){
Log.e(TAG, "Cannot write document to database", e);
}
}
And get all datas from Couchbase Lite:
Query allDocumentsQuery= cbDatabase.createAllDocumentsQuery();
QueryEnumerator queryResult=allDocumentsQuery.run();
for (Iterator<QueryRow> it=queryResult;it.hasNext();){
QueryRow row=it.next();
Document doc=row.getDocument();
String id=doc.getId(); // I get the id in here but the result is the default id (UUID):(
}
So, I have two questions:
When I query all documents from database (couchbase lite), the document is returned which the default id (UUID), Why it is not return my custom ID?
( means: Saving all the document to database which custom ids: 1, 2, 3 ......9. But the result of all documents when get from database have default ids: UUID, UUID,..., UUID. )
I dont understand Why I save the document in order but the return of all documents are not in order ? (because this reason make me custom id of document)
Please give me some advises or guide me on the best way to do this. Thank you all so much.
You need to add the _rev property to your map with the id as value.
Here's an excerpt from the documentation:
putProperties(Map<String, Object> properties)
Creates and saves a new Revision with the specified properties. To succeed the specified properties must include a '_rev' property whose value maches the current Revision's id.
So your code should look like this:
Map<String,Object> docContent= new HashMap<String, Object>();
docContent.put("_rev", String.valueOf(i));
docContent.put("title", title);
docContent.put("firstName", firstName);
docContent.put("lastName", lastName);

Create Product in MS Dynamics CRM 2011 via SOAP/Java

I generated all required java classes from crm.dynamics.com/XRMServices/2011/Discovery.svc?wsdl and crm.dynamics.com/XRMServices/2011/Organization.svc?wsdl schemas.
I authenticated in CRM with LiveId.
Now i need to create Product in Product Catalog. Here is code for this:
Entity newEntryInfo = new Entity();
AttributeCollection collection = new AttributeCollection();
addAttribute(collection, "name", "Tama Starclassic Performer");
addAttribute(collection, "productnumber", "1");
addAttribute(collection, "price", createMoney("100.0"));
addAttribute(collection, "isstockitem", Boolean.TRUE);
addAttribute(collection, "statuscode", 1);
newEntryInfo.setAttributes(collection);
newEntryInfo.setLogicalName("product");
Guid productGuid = serviceStub.create(newEntryInfo);
private void addAttribute(AttributeCollection collection, String key, Object value) {
KeyValuePairOfstringanyType values = new KeyValuePairOfstringanyType();
values.setKey(key);
values.setValue(value);
collection.addKeyValuePairOfstringanyType(values);
}
Execution shows error "The unit schedule id is missing."
Looks like i need to provide "Unit Group" and "Default Unit" for new product.
Question: How can i set those values? Should i use RelatedEntities (how create it) or Attributes (how create it)
As it is a lookup on the form, you should be able to set the value with an EntityReference.
Using your methods that would be:
addAttribute(collection, "fieldName", new EntityReference("entityName", new Guid("id"))
Where:
fieldName is the schema name of the field you want to populate
entityName is the schema name of the entity you want to populate the field with
id is the Guid of a record which is the same type as entityName.
To put that into a context (where I happen to know the schema names off the top of my head).
//Create a new contact first
Entity contact = new Entity("contact");
contact["lastname"] = "Wood";
Guid contactId = service.Create(contact);
//Create an incident/case which links to that new contact
Entity incident = new Entity("incident");
incident["customerid"] = new EntityReference("contact", contactId)
service.Create(incident)
As a side is there a particular reason you are using a such a long winded code style? The entity class has an index which links to underlying attribute dictionary. Its a bit more straight forward.
If you are looking for more examples check out: Use the Late Bound Entity Class in Code

Returning the ID of a blank object during creation process

I would like to make an object, get its '_id', change it to a String and pass that as an argument to another object.
Thoughts were something like this, but its not working
BasicDBObject doc = new BasicDBObject();
a.insert(doc);
String id = doc.getString("$oid");
You can do this:
ObjectId myId = new ObjectId(); //id is created here
DBObject myObject = new BasicDBObject();
myObject.put("_id", myId);
// Whether you save myObject to Mongo or not at this moment, you have its id
String myIdString = myId.toString();
// Now you can save myObject's id string in another object, and then later on,
// If you want to recreate the myId object you can do so:
ObjectId myIdRecreated = new ObjectId(myIdString);
In other words, instantiating an ObjectId and passing it to the "_id" field of a DBObject will mean that that ObjectId will be the id for that DBObject. In this way you don't need to explicitly save the DBObject to Mongo to have its id.

Categories