If we wanna get an object ID we should do this:
String objectId = gameScore.getObjectId();
but what if we wanna get an object ID by a query? Like this:
ParseQuery<ParseObject> query = ParseQuery.getQuery("mytable");
query.whereEqualTo("Title", "Adrians Book");
List<ParseObject> results = null;
try {
results = query.find();
if(!results.isEmpty()) {
String objectId = results.getObjectId();
}
} catch (com.parse4cn1.ParseException e) {
Dialog.show("Err", "Something went wrong.", "OK", null);
}
Sounds interesting don't you think? I wish it could be possible. As you can see in this example the query will get a value from a specific object in the table which could track for the object ID then returning it as well. ParseQuery class should be implemented with getObjectId(). Because by this way applications always could have access to object IDs from the query even after applications get restarted so in the first example the gameScore which is actually an instance of ParseObject would lost reference to the Database after restarting. Getting object IDs by the query it would be able to program applications to get object IDs automatically without the need of doing it manually nor depending on instances of ParseObject.
#Shai Almog: Thank you very much for taking your time to look at the ParseQuery documentation.
I accidentally figured out how to get this done!
ParseQuery<ParseObject> query = ParseQuery.getQuery("mytable");
query.whereEqualTo("Title", "Adrians Book");
List<ParseObject> results = null;
try {
results = query.find();
if(!results.isEmpty()) {
String objectId = results.get(0).getObjectId();
System.out.println(objectId);
}
} catch (com.parse4cn1.ParseException e) {
Dialog.show("Err", "Something went wrong.", "OK", null);
}
Yep, after adding the method .get(index) it allows you to access the method .getObjectId() since results is a list of a ParseObject, then the respective objectId of your query result will be printed in the console! I'm pretty glad it's working because I won't need to serialize each object for now which would be a pain.
Also if you wanna set an instance of ParseObject with an existing objectId in case you need to update something in your Database, you can use this example:
ParseObject po = ParseObject.create("mytable");
po.setObjectId(//YOUR DESIRED OBJECTID HERE, AS LONG AS IT EXISTS IN THE DATABASE);
As far as I know you need to get the whole object then query it's ID. I don't see a query id method here https://github.com/sidiabale/parse4cn1/blob/41fe491699e604fc6de46267479f47bc422d8978/src/com/parse4cn1/ParseQuery.java
Related
Im trying to use the findDistinct function from mongoTemplate but i always retrieve an empty result list.
Can you help me out to spot the problem ? Or maybe you have a simpliest way to do it
NB:
I do have data in my collection
(on a basic find, i fetch more than 300 results in the list but all of this result are the same excepting on one key, i want all the distinct object from their NAME value for instance )
I tryied this :
List<DiffusionListImpl> list = new ArrayList<>();
try{
query = new Query(Criteria.where("CUSTOMERNUMBER").is(1));
list = mongoTemplate.findDistinct(query, KeyWhereIWantTheDistinct, collectionName,
KlassResultModel.class);
} catch (MongoException e) {
logger.error("MongoException: " + e);
} catch (Exception e) {
logger.error("Error: " + e);
}
return list;
My bad, i misread the documentation.
But i find it akward to have this kind of comportement of this function.
I have to make a call to the DB to fetch a list of distinct value and then make another Call of the same DB to retrieve the object.
Is there any way to do it in one call? (Performance issue)
It can be done in one DB call, use below code.
final List<DiffusionListImpl> result =
IteratorUtils.toList(this.mongoTemplate.getCollection("collectionName")
.distinct("fieldName", query.getQueryObject(), DiffusionListImpl.class)
.iterator());
for IteratorUtils you can use apache
import org.apache.commons.collections4.IteratorUtils;
I'm making a game (trying...) like Risk for college with Spring MVC. I'm using JPA and I need to save the state of the game (whose player turn is, units in countries,etc.) in a String field coded with JSON, and that's what's driving me crazy.
First, I create the game with other information (id, user's owner, state...) and when It starts for the first time I want to generate the JSON and set it to the entity and save it. I tried with entityManager.merge(game) but when I look at the DB the JSON field is null. I tried to make namedquery and nativequery but at the JSON string have " it's a mess.
Any ideas why it's not saving with merge?
The code is something like:
HomeController.class
public String getGame(#PathVariable("idGame") long idGame,
Model model) throws IOException {
Game g = GameDao.getGame(idGame);
if (g.getJson == null) {
g.initializeGame(); // it sets the json attribute
GameDao.update(entityManager, g);
}
}
GameDAO.class
#Transactional
public static Game update(EntityManager entityManager, Game g) {
try {
entityManager.merge(g); // if I debug here g has the json attribute setted
return entityManager.find(Game.class, g.getId()); // the game object that's returned hasn't the json field setted
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
This is the repo https://github.com/alvardsoler/reinvasion but it's the most in Spanish. It's for september exams and I don't have too much time so I want to do it very sketchy first, and then if I have time I'll do it good. If I can't save the JSON info in the DB I will save it in a file in the server with the id of the game or something like that.
I found the problem. I make the update with createNativeQuery:
Query q = entityManager.createNativeQuery("update Game g SET g.json=:json where g.id=:id");
q.setParameter("json", g.getJson());
q.setParameter("id", g.getId());
q.executeUpdate();
And added #Transactional in the GameDAO's method and in the HomeController method...
It is rather easy using the library GSON (jsonString ):
// Create the JSON string like this first
MyObject yourObject = /* Create an object here */;
Gson gson = new Gson();
String jsonString = gson.toJson(yourObject);
// Create an object from the JSON string like this afterwards
MyObject newObject = gson.fromJson(jsonString , MyObject.class);
{
"question":"what is your color?",
"choices":[{"option":"yello"},{"option":"blue"}],
"creation-date":"2014-04-13",
"expiry date":"2014-04-14"
}
In order to retrive list of polls
public List<Poll> getPolls()
{
try {
mongoClient=new MongoClient("NavDeep",27017);
db=mongoClient.getDB("sms-voting");
collection=db.getCollection("pollsCollection");
} catch(Exception e){
e.printStackTrace();
}
List<Poll> polls = new ArrayList<Poll>();
DBCursor cursor=collection.find();
while(cursor.hasNext())
{
DBObject object = cursor.next();
what should i write in order to retrieve List<Poll>????
}
}
mongoClient.close();
return polls;
}
but i am getting null pointer exception near BasicDBList pollList=(BasicDBList)object.get("pollsCollection");
Can any body please Help me out.What should i actually write inside get()??
Thnks,
deepthi
I think the problem could be that you're doing cursor.next() twice in the lines above, pulling two records at a time.
What if you try:
polls.add(object)
instead of
polls.add(cursor.next())
Rather than iterating the cursor you appear to want the .toArray() method:
DBCursor cursor = collection.find();
List<DBObject> list = cursor.toArray();
Generally cursors are a good idea, and you probably should be building any array type results from within that loop. But this is a way to change the cursor.
I need to insert a list of objects with a predefined _id (Long) into a collection.
insert(object) method for a single object from AdvancedDatastore works great. The trouble begins when i try to use the insert() method which accepts an Iterable. Here is a sample piece of code:
try {
advancedDatastore.insert("collection_name", feeds, WriteConcern.ERRORS_IGNORED);
} catch (Exception e) {
e.printStackTrace();
}
I guess that this code is supposed to ignore errors (an object with a duplicate id already exists in the collection) and just continue with the next item, but it does not. And no exception is raised.
Thanks!
Update:
This code inserts all the elements, but "1" is not printed out.
try {
System.err.println(0);
advancedDatastore.insert("collection_name", feeds, WriteConcern.ERRORS_IGNORED.continueOnErrorForInsert(true));
System.err.println(1);
} catch (Exception e) {
e.printStackTrace();
}
Update2:
Sorry, the code completes properly and "1" is printed out, but it takes tremendously more time than single inserts. In my case 35_000 inserts 1 by one - 3 seconds, in batch - 100+ seconds
Update3:
So far the best way to deal with the issue for me is to use native java driver for mongodb.
1st I convert my object list to DBObject list:
final List<DBObject> dbObjects = new ArrayList<DBObject>();
for (MyObject object: objectList) {
dbObjects.add(morphia.toDBObject(object));
}
Then I insert through mongo DB instance:
db.getCollection("collection_name").insert(dbObjects, WriteConcern.UNACKNOWLEDGED.continueOnErrorForInsert(true));
Performace for inserting 150_000 objects:
Native DB insert: 2-3 seconds
via Morphia's insert(object): 15+ seconds
via Morphia's insert(Iterable): 400+ seconds
A better way would be appreciated.
It works to me in this way
final List<DBObject> dbObjects = new ArrayList<DBObject>();
try {
TypedQuery<RegistroCivil> consulta = em.createQuery("select p from RegistroCivil p", RegistroCivil.class);
List<RegistroCivil> lista = consulta.getResultList();
for (RegistroCivil object : lista) {
dbObjects.add(morphia.toDBObject(object));
}
long start = System.currentTimeMillis();
ds.getCollection(RegistroCivil.class).insert(dbObjects);
//ds.save(lista);
long end = System.currentTimeMillis();
tmongo = end - start;
I'm to get a list of the users photos (one's they've been tagged in) using FQL.
Basically I've go an array object like so: _imageAddressArray.
I can retrieve the users' photos using graphApi so I know it works, problem with graphAPi is that it's too slow (+15 seconds min for 100 photos).
So far I've got:
//New Stuff
FQL fql = new FQL(facebook);
String FQLResult = null;
try
{
_userGallery = graphApi.getPhotosMy(_noOfPhotos);
FQLResult = fql.fqlQuery("SELECT object_id, src_small FROM photo");
}
catch (EasyFacebookError e)
{
e.printStackTrace();
}
System.out.println("FQL Result" + FQLResult);
This returns the error: 601, any ideas anyone?
Of course ideally FQLResult will be a string[] (string array)
You're getting an error because you don't have a WHERE clause in your FQL statement that references one of the indexed columns -- shown with a "*" here
To get the photos using FQL that your user has been tagged in, try this:
SELECT object_id, src_small FROM photo WHERE object_id IN
(SELECT object_id FROM photo_tag WHERE subject = me())