I am apparently confused as to how the GAE ancestor query should work. My understanding was that an ancestor query should return all descendent generations, not just immediate children. Yet if I modify the example from the Developer Guide as follows, I retrieve only the immediate children, never the grandchild. What am I missing?
Entity person = new Entity("Person", "tom");
Entity weddingPhoto = new Entity("Photo", person.getKey());
weddingPhoto.setProperty("imageUrl",
"http://domain.com/some/path/to/wedding_photo.jpg");
Entity babyPhoto = new Entity("Photo", person.getKey());
babyPhoto.setProperty("imageUrl",
"http://domain.com/some/path/to/baby_photo.jpg");
// add this grandchild:
Entity grandbabyPhoto = new Entity("Photo", babyPhoto.getKey());
grandbabyPhoto.setProperty("imageUrl",
"http://domain.com/some/path/to/grandbabyPhoto.jpg");
Entity dancePhoto = new Entity("Photo", person.getKey());
dancePhoto.setProperty("imageUrl",
"http://domain.com/some/path/to/dance_photo.jpg");
Entity campingPhoto = new Entity("Photo");
campingPhoto.setProperty("imageUrl",
"http://domain.com/some/path/to/camping_photo.jpg");
getDatastore().put(
java.util.Arrays.asList(person, weddingPhoto, babyPhoto, dancePhoto, campingPhoto));
Query userPhotosQuery = new Query("Photo");
userPhotosQuery.setAncestor(person.getKey());
// This returns weddingPhoto, babyPhoto and dancePhoto, but
// not grandbabyPhoto --- why???
List<Entity> results =
getDatastore().prepare(userPhotosQuery).asList(
FetchOptions.Builder.withDefaults());
Thanks very much for any help you can provide!
Because your put(..) statement does not contain grandbabyPhoto, so it does not get saved.
Related
i am getiing proper values from DB but Getting Duplicate List Values while add list object to class object, in Spring Boot
Please suggest to me how to do it.
Get data from DB Code : Here Rooms is my DB Entity class
CriteriaBuilder roomsBuilder = roomSession.getCriteriaBuilder();
CriteriaQuery<Rooms> query = roomsBuilder.createQuery(Rooms.class);
Root<Rooms> root = query.from(Rooms.class);
Predicate userRestriction = roomsBuilder.or(roomsBuilder.notEqual(root.get(SmatrEntityParameters.IS_DELETED), "Y"),
roomsBuilder.isNull(root.get(SmatrEntityParameters.IS_DELETED)));
Predicate userRestriction2 = roomsBuilder.and(roomsBuilder.equal(root.join("properties").get(SmatrEntityParameters.PROPERTY_ID), propertyId));
query.where(roomsBuilder.and(userRestriction, userRestriction2));
Query q = roomSession.createQuery(query);
List<Rooms> getroomslistobj= q.getResultList();
Iterate the list code: Here getAllRoomsobj means main response pojo class
List<GetAllRooms> getallroomslistobj = new ArrayList<GetAllRooms>();
for (int i = 0; i < getroomslistobj.size(); i++) {
int dbroomId = getroomslistobj.get(i).getRoomId();
String dbroomName = getroomslistobj.get(i).getRoomName();
// Actual code start
getAllRoomsobj.setRoomId(dbroomId);
getAllRoomsobj.setRoomName(dbroomName);
getallroomslistobj.add(getAllRoomsobj);
// Actual code end
}
I tried one code at the middle of the Actual code but I did not want create a new object for the response class:
GetAllRooms object = new GetAllRooms();
object.setRoomId(dbroomId);
object.setRoomName(dbroomName);
getallroomslistobj.add(object);
Please Help me Out,
Thanks in Advance
u can try it by stream.map() of java8
Sorry for my English.
I'm working on an android application that stores data on the Datastore Google cloud. I want to carry out a query on my datastore that mixes StContainsFilter and FilterPredicate. It does not work! Here is my code:
DatastoreService service = DatastoreServiceFactory.getDatastoreService();
Query q = new Query("utilisateurs");
Query.Filter filtrage1 = new Query.FilterPredicate("sexe", Query.FilterOperator.EQUAL, "M");
Query.Filter filtrage2 = new Query.FilterPredicate("datenaissance", Query.FilterOperator.LESS_THAN_OR_EQUAL, datemin);
Query.Filter filtrage3 = new Query.FilterPredicate("datenaissance", Query.FilterOperator.GREATER_THAN_OR_EQUAL, datemax);
GeoPt center = new GeoPt(Float.parseFloat(lat), Float.parseFloat(lng));
double radius = km*1000;
Query.Filter filtrage4 = new Query.StContainsFilter("location", new GeoRegion.Circle(center, radius));
Query.Filter present = Query.CompositeFilterOperator.and(filtrage2,filtrage3,filtrage1,filtrage4);
q.setFilter(present);
PreparedQuery pq = service.prepare(q);
List<Entity> results = pq.asList(FetchOptions.Builder.withDefaults());
To mix different filters you can use a CompositeFilter. You can read more about Datastore Queries here. With the CompositeFilter, you can connect multiple Filters, which then act as one. However, you still have to consider not to set inequality Filters on more than one property.
To create a CompositeFilter use this syntax:
CompositeFilter nameOfFilter = CompositeFilterOperator.and(Collection<Filter>);
Collection can also be a List, an Array or you can seperate Filters by comma
Here an example on how to create a CompositeFilter:
Filter filter1 = new FilterPredicate("someProperty", FilterOperator.Equal, someValue)
Filter filtrage4 = new StContainsFilter("location", new GeoRegion.Circle(center, radius));
Filter filtrage2 = new FilterPredicate("datenaissance", Query.FilterOperator.LESS_THAN_OR_EQUAL, datemin);
CompositeFilter filter = CompositeFilterOperator.or(filter1, filtrage4, filtrage2);
Use CompositeFilterOperator.and if you need all Filters to apply and .or if one applying Filter is enough.
Technically your solution should work because StContainsFilter is a direct subclass from Query.Filter. The reason for your problem is a wrong import. You should check your imports and change them if they say anything with "repackaged" (I hade the same problem too)
Hello I'm newbie in learning hibernate framework. I was solved my error but I don't know what the problem happen. In my project I have 2 tables Tblbarang and Tbljenis. And 1 field at Tblbarang had relations as foreign key by Tbljenis.
I want to update Tblbarang table. I had two method
private void getcombobarang() {
Query q = sess.createQuery("from Tblbarang");
arrbarang = new ArrayList<>();
DefaultComboBoxModel comboModel = new DefaultComboBoxModel();
for (Object o : q.list()) {
Tblbarang coba = (Tblbarang) o;
comboModel.addElement(coba.getNamabarang());
arrbarang.add(coba);
}
combobarang.setModel(comboModel);
}
This method to set model combobox which I would choose to set the table Tblbarang item.
and now this method to update my Table Tblbarang
sess = NewHibernateUtil.getSessionFactory().openSession();
sess.beginTransaction();
Tblbarang tb = new Tblbarang();
tb.setKodbarang(arrbarang.get(combobarang.getSelectedIndex()).getKodbarang());
tb.setNamabarang(arrbarang.get(combobarang.getSelectedIndex()).getNamabarang());
tb.setTbljenis(arrbarang.get(combobarang.getSelectedIndex()).getTbljenis());
tb.setHarganet(arrbarang.get(combobarang.getSelectedIndex()).getHarganet());
tb.setHargajual(arrbarang.get(combobarang.getSelectedIndex()).getHargajual());
System.out.println(arrbarang.get(combobarang.getSelectedIndex()).getTbljenis()); // <-- this line resolved my problem
int st = Integer.parseInt(stok.getText()) ;
int jm = Integer.parseInt(jumlah.getText());
String totss = String.valueOf(st + jm);
Short totstok = Short.parseShort(totss);
tb.setStok(totstok);
sess.update(tb);
sess.getTransaction().commit();
when without System.out.print() the error are following
org.hibernate.HibernateException: illegally attempted to associate a proxy with two open Sessions
at org.hibernate.proxy.AbstractLazyInitializer.setSession(AbstractLazyInitializer.java:126)
at org.hibernate.proxy.AbstractLazyInitializer.setSession(AbstractLazyInitializer.java:126)
at org.hibernate.engine.StatefulPersistenceContext.reassociateProxy(StatefulPersistenceContext.java:573)
at org.hibernate.engine.StatefulPersistenceContext.reassociateIfUninitializedProxy(StatefulPersistenceContext.java:533)
at org.hibernate.event.def.ProxyVisitor.processEntity(ProxyVisitor.java:50)
at org.hibernate.event.def.AbstractVisitor.processValue(AbstractVisitor.java:125)
at org.hibernate.event.def.AbstractVisitor.processValue(AbstractVisitor.java:83)
at org.hibernate.event.def.AbstractVisitor.processEntityPropertyValues(AbstractVisitor.java:77)
at org.hibernate.event.def.AbstractVisitor.process(AbstractVisitor.java:144)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.performUpdate(DefaultSaveOrUpdateEventListener.java:314)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsDetached(DefaultSaveOrUpdateEventListener.java:246)
at org.hibernate.event.def.DefaultUpdateEventListener.performSaveOrUpdate(DefaultUpdateEventListener.java:57)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93)
at org.hibernate.impl.SessionImpl.fireUpdate(SessionImpl.java:742)
at org.hibernate.impl.SessionImpl.update(SessionImpl.java:730)
at org.hibernate.impl.SessionImpl.update(SessionImpl.java:722)
at retail.ui.frmBarangMasuk.tambahitemActionPerformed(frmBarangMasuk.java:622) //<-this line directing to sess.update(tb)
I will simply my code like this
sess = NewHibernateUtil.getSessionFactory().openSession();
sess.beginTransaction();
Tblbarang tb = (Tblbarang) arrbarang.get(combobarang.getSelectedIndex());
System.out.println(arrbarang.get(combobarang.getSelectedIndex()).getTbljenis());
int st = Integer.parseInt(stok.getText()) ;
int jm = Integer.parseInt(jumlah.getText());
String totss = String.valueOf(st + jm);
Short totstok = Short.parseShort(totss);
tb.setStok(totstok);
sess.update(tb);
sess.getTransaction().commit();
but the exception showing same error. I want to know what happen with my code? anyone can explain with that issue or this is bug from hibernate, thanks
In getcombobarang, you have a sess(session1) to get objects from database. And when updating tb, you open another sess(session2).
If Tblbarang contains a foreign-key object, in this case, which must associates with session1, because it's obtained from the function getcombobarang at first. So sess.update() throws an exception as you have seen.
For solution:
use merge() instead of update()
before update, copy the foreign-key object's properties to a whole new object, then set it into tb
I'm also confused about the impact of System.println() here.
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
Can someone please tell me how to get a Text value out of a Google App Engine datastore using Java? I have some entities in the datastore with a Text property named longDescription. When I try this:
DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
Query q = new Query("Items");
PreparedQuery pq = ds.prepare(q);
for (Entity result : pq.asIterable()) {
Text longDescription = (Text)result.getProperty("longDescription");
}
I'm getting this warning on the longDescription assignment line:
WARNING: /pstest
java.lang.ClassCastException: java.lang.String cannot be cast to
com.google.appengine.api.datastore.Text
I'm absolutely bumfuzzled here. The only string in my code is the literal "longDescription" that is used to fetch the correct property. If I put this just above the assignment line:
log.warning("Type is " + (result.getProperty("longDescription")).getClass());
I see the following output:
WARNING: Type is class com.google.appengine.api.datastore.Text
Okay, so result.getProperty("longDescription") really, really is a Text object that is being passed back as an object. I've even tried using the fully qualified name (com.google.appengine.api.datastore.Text) instead of just Text with the same results. Where is the String cast coming in? And more importantly, how do I get that Text out of the datastore? I'm at my wit's end here, and any help would be appreciated!
Oh, one other possibly relevant note: This is the assignment I used when inserting the property into the datastore:
Entity eItem = new Entity("Items");
eItem.setProperty("longDescription", new Text(req.getParameter("ldes")));
ds.put(eItem);
When I look at the description in my management console, it seems to be over 500 characters, and it's displayed like this:
<Text: This is a long form description of an item in the store that is access...>
Did I screw something up when inserting it? If so, how do you insert Text items into the datastore?
I figured out the problem, Wei Hao was right in the comments above. It seems that at some point, I inserted a test String as a longDescription instead of a Text. I'm going to chalk this up to being a lesson learned from the school of hard knocks due to being a bit of a noob with the datastore.
For anyone else who runs across this question, the answer is: If you're iterating over a list of query results, make sure that you're getting back what you expect on every result that comes back! Remember, this isn't an RDBMS and every entity can have a different datatype for the same property. So yes, you can have 1,572,394 entities in which longDescription is a Text and one entity in which longDescription is a String, and this will hose you up.
Here's a little code snippet that probably would help to diagnose this issue:
DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
Query q = new Query("Items");
PreparedQuery pq = ds.prepare(q);
for (Entity result : pq.asIterable()) {
if (longDescription isinstanceof Text)
Text longDescription = (Text)result.getProperty("longDescription");
else
log.severe("Unexpected datatype: longDescription is a "
+ result.getProperty("longDescription").getClass().toString());
}
Here's my code;
DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
Query q = new Query(entityKind);
PreparedQuery pq = ds.prepare(q);
for (Entity e : pq.asIterable()) {
String longtext = ((Text)e.getProperty("somelongdescription")).getValue();}