문제

Ok so I have an application that uses GAE and consequently the datastore.

Say I have multiple companies A, B and C and I have within each company Employees X,Y and Z. The relationship between a company and employee will be OneToMany, with the company being the owner. This results in the Company Key being of the form

long id = 4504699138998272; // Random Example 
Key CompanyKey = KeyFactory.createKey(Company.class.getSimpleName(), id);

and the employee key would be of the form

long id2 = 5630599045840896;
Key EmployeeKey = KeyFactory.createKey(CompanyKey,Employee.class.getSimpleName(),id2);

all fine and well and there is no problem, until in the front end, during jsp representation. Sometimes I would need to generate a report, or open an Employees profile, in which case the div containing his information would get an id as follows

<div class="employeeInfo" id="<%=employee.getKey().getId()%>" > .....</div>

and this div has an onclick / submit event, that will ajax the new modifications to the employee profile to servelet, at which point I have to specify the primary key of the employee, (which I thought I could easily get from the div id), but it didnt work server side.

The problem is I know the Employees String portion of the Key and the long portion, but not the Parent key. To save time I tried this and it didnt work

Key key = KeyFactory.creatKey(Employee.class.getSimpleName(); id);
Employee X = em.find(Employee.class,key);

X is always returned null.

I would really appreciate any idea of how to find or "query" Entities by keys without knowing their parents key (as I would hate having to re-adjust Entity classes)

Thanks alot !!

도움이 되었습니까?

해결책

An Entity key and its parents cannot be separated. It's called ancestor path, a chain composed of entity kinds and ids.

So, in your example ancestor paths will look like this:

  • CompanyKey: ("Company", 4504699138998272)
  • EmployeeKey: ("Company", 4504699138998272, "Employee", 5630599045840896)

A key composed only of ("Employee", 5630599045840896) is a completely different one comparing to the EmployeeKey even though both keys end with the same values. Think of concatenating elements into a single "string" and comparing final values, they will never match.

One thing you can do is use encoded keys instead of their id values:

String encodedKey = KeyFactory.keyToString(EmployeeKey);
Key decodedKey = KeyFactory.stringToKey(encodedKey);
decodedKey.equals(EmployeeKey); // true

More about Ancestor Paths: https://developers.google.com/appengine/docs/java/datastore/entities#Java_Ancestor_paths

KeyFactory Java doc: https://developers.google.com/appengine/docs/java/javadoc/com/google/appengine/api/datastore/KeyFactory#keyToString(com.google.appengine.api.datastore.Key)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top