Problems with queryBuilder greenDAO - java

I am using latest version of GreenDAO... I am missing something on using the data from the DB.
I need to prevent the creation of records that have the same PROFILE_NUMBER. Currently during testing I have inserted 1 record with the PROFILE_NUMBER of 1.
I need someone to show me an example of how to obtain the actual value of the field from the db.
I am using this
SvecPoleDao svecPoleDao = daoSession.getSvecPoleDao();
List poles = svecPoleDao.queryBuilder().where(SvecPoleDao.Properties.Profile_number.eq(1)).list();
and it obtains something... this.
[com.example.bobby.poleattachmenttest2_workingdatabase.db.SvecPole#bfe830c3.2]
Is this serialized? The actual value I am looking for here is 1.

Here is the solution.You'll need to use listlazy() instead of list().
List<SvecPole> poles = svecPoleDao.queryBuilder().where(SvecPoleDao.Properties.Profile_number.eq(1)).listLazy();

Related

Finding a list of related objects by ID

Let's say for example I have a bridge table called PersonAnimal. I want to search for all the people who have a given animal's ID. The query so far looks like:
Animal animal = getById(Animal.class, animalId)
ObjectSelect
.query(PersonAnimal.class)
.where(PersonAnimal.ANIMAL.eq(animal))
.select(context)
However the first line in the above code segment shows that I first have to retrieve the related object from the database. I want to get rid of that database lookup and instead do something like:
ObjectSelect
.query(PersonAnimal.class)
.where(PersonAnimal.ANIMAL_ID.eq(animalId)) // <- Find by ID instead
.select(context)
Is that possible?
I am running version 4.1 of the Apache Cayenne ORM.
Just as I posted the question I found the answer. You need to create an Expression using a Property object like so:
val findByIdExpr = Property.create(PersonAnimal.ANIMAL.name, Long::class.java).eq(yourId)
val gotList = ObjectSelect
.query(PersonAnimal.class)
.where(findByIdExpr)
.select(context)
Above code is in Kotlin but is also easy to understand from a Java perspective.

Morphia update document with undefined number of fields

I'm working on a small project using morphia for MongoDB. I want to know what is the best way to update a document without knowing first hand what field to update. Say for example, I have a form, after having saved to database I might want to come back and change some fields but I haven't decided yet what to change.
My current solution is doing an update for all fields whether it is changed or not and of course it throws null exception. Morphia complains on null value update.
My code looks like this:
Query<Project> q = datastore.find(Project.class, "_id", projectToUpdate.getId());
UpdateOperations<Project> update
= datastore.createUpdateOperations(Project.class)
.set("name", updatedProject.getName())
.set("deadline", updatedProject.getDeadline())
.set("priority", updatedProject.getPriority())
.set("completion", updatedProject.getCompletion())
.set("description", updatedProject.getDescription())
.set("projectManager", updatedProject.getPM())
.set("collaborators", updatedProject.getAllCollaborators())
.set("teams", updatedProject.getAllTeams())
.set("userStories", updatedProject.getUserStories())
.set("log", updatedProject.getLog());
datastore.findAndModify(q, update);
Exception
Exception in thread "main" org.mongodb.morphia.query.QueryException: Value cannot be null.
at org.mongodb.morphia.query.UpdateOpsImpl.set(UpdateOpsImpl.java:220)
at controllers.QueryProjects.updateProject(QueryProjects.java:78)
at controllers.DBConnection.TestMongo(DBConnection.java:152)
at penelope.Main.main(Main.java:12)
I was thinking about using delegate/event handler to update each field individually but I'm afraid that might degrade the performance.
You should just use datastore.save(). See an example at http://mongodb.github.io/morphia/1.3/getting-started/quick-tour/

Java ResultSet giving returning wrong values for some columns

I have an applicaton that executes a query using NamedParameterJdbcTemplate. The resultSet is then parsed row by row using ResultSet.next().
Now in some cases during multi threading scenarios, this goes wrong. The result set is returning wrong values. When I execute the same query in SQLDeveloper, I am seeing the correct values. Not sure what could be the problem behind this.
while (rs.next()) {
count++;
long dbKy = rs.getLong("DBKY");
pAttrs = map.get(dbKy );
if (pAttrs== null) {
pAttrs= new HashMap<String, String>();
map.put(dbKy , pAttrs);
}
log.info( "PrintingResultSet!!::"+rs.getLong("DBKY")
+"::"+rs.getString(ATTR_NAME)
+"::"+rs.getString(ATTR_VAL)
+"::"+rs.getString(Constants.VAL));
pAttrs.put(rs.getString(ATTR_NAME),rs.getString(ATTR_VAL));
}
EDIT: This code is in the repo layer of SpringBoot application. Multithreading is, this issue happens when multiple requests are sent simultaneously. I have printed Thread id in my logs and it confirms that this happens only in multi threaded scenarios.
The value that is being returned actually is the value of some other row.
What values (wrong values) do you see when you are trying to display the resultset. If you see some unknown texts or symbols then probably it could be "encoding" issue. I suggest you to please refer on how to encode values like some special characters/symbols on your service layer since no doubt you will be able to see the data in the database by using the query but if that data contains some special characters/symbols then there is a need of encoding "UTF-8".
Thanks!

Failed to make bulk upsert using mongo

I'm trying to do upsert using mongodb driver, here is a code:
BulkWriteOperation builder = coll.initializeUnorderedBulkOperation();
DBObject toDBObject;
for (T entity : entities) {
toDBObject = morphia.toDBObject(entity);
builder.find(toDBObject).upsert().replaceOne(toDBObject);
}
BulkWriteResult result = builder.execute();
where "entity" is morphia object. When I'm running the code first time (there are no entities in the DB, so all of the queries should be insert) it works fine and I see the entities in the database with generated _id field. Second run I'm changing some fields and trying to save changed entities and then I receive the folowing error from mongo:
E11000 duplicate key error collection: statistics.counters index: _id_ dup key: { : ObjectId('56adfbf43d801b870e63be29') }
what I forgot to configure in my example?
I don't know the structure of dbObject, but that bulk Upsert needs a valid query in order to work.
Let's say, for example, that you have a unique (_id) property called "id". A valid query would look like:
builder.find({id: toDBObject.id}).upsert().replaceOne(toDBObject);
This way, the engine can (a) find an object to update and then (b) update it (or, insert if the object wasn't found). Of course, you need the Java syntax for find, but same rule applies: make sure your .find will find something, then do an update.
I believe (just a guess) that the way it's written now will find "all" docs and try to update the first one ... but the behavior you are describing suggests it's finding "no doc" and attempting an insert.

Unable to retrive Projection/Multi- Relantion field Requests.Custom_SFDCChangeReqID2 using versionone java sdk

I have been trying to retrieve information from querying a specific Asset(Story/Defect) on V1 using the VersionOne.SDK.Java.APIClient. I have been able to retrieve information like ID.Number, Status.Name but not Requests.Custom_SFDCChangeReqID2 under a Story or a Defect.
I check the metadata for:
https://.../Story?xsl=api.xsl
https://.../meta.V1/Defect?xsl=api.xsl
https://.../meta.V1/Request?xsl=api.xsl
And the naming and information looks right.
Here is my code:
IAssetType type = metaModel.getAssetType("Story");
IAttributeDefinition requestCRIDAttribute = type.getAttributeDefinition("Requests.Custom_SFDCChangeReqID2");
IAttributeDefinition idNumberAttribute = type.getAttributeDefinition("ID.Number")
Query query = new Query(type);
query.getSelection().add(requestCRIDAttribute);
query.getSelection().add(idNumberAttribute);
Asset[] results = v1Api.retrieve(query).getAssets();
String RequestCRID= result.getAttribute(requestCRIDAttribute).getValue().toString();
String IdNumber= result.getAttribute(idNumberAttribute).getValue().toString();
At this point, I can get some values for ID.Number but I am not able to retrieving any information for the value Custom_SFDCChangeReqID2.
When I run the restful query to retrieve information using a browser from a server standpoint it works and it does retrieve the information I am looking for. I used this syntax:
https://.../rest-1.v1/Data/Story?sel=Number,ID,Story.Requests.Custom_SFDCChangeReqID2,Story.
Alex: Remember that Results is an array of Asset´s, so I guess you should be accessing the information using something like
String RequestCRID= results[0].getAttribute(requestCRIDAttribute).getValue().toString();
String IdNumber= results[0].getAttribute(idNumberAttribute).getValue().toString();
or Iterate through the array.
Also notice that you have defined:
Asset[] results and not result
Hi thanks for your answer! I completely forgot about representing the loop, I was too focus on the retriving information part, yes I was actually using a loop and yes I created a temporary variable to check what I was getting from the query in the form
Because I was getting the variables one by one so I was only using the first record. My code works after all. It was just that What I was querying didn't contain any information of my use, that's why I was not finding any. Anyway thanks for your comment and observations

Categories

Resources