How to retrieve Google Appengine Objects by id (Lo

2019-07-06 17:29发布

i have declared an entity the following way:

public class MyEntity {
 @PrimaryKey
 @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
 private Long id;
 @Persistent
 private String text;
        //getters and setters
}

Now I want to retrieve the objects using the id. I tried to manage it from the Google Appengine Data Viewer with "SELECT * FROM MyEntity Where id = 382005" or via a query in a servlet. I get no results returned. But i know for sure that the object with the id exists (i made a jsp which queries all objects in the db and displays them in the db).

So what is wrong in my query? Am I querying the wrong field? The Google Appengine Data Viewer names the field "ID/name" and it has the value "id=382005". Do I have to query with this names? I've tried but it didn't work out :(

1条回答
萌系小妹纸
2楼-- · 2019-07-06 17:52

You can use below since you are querying using the primary key:

MyEntity yourEntity = entityManager.find(MyEntity.class, yourId);

Note, this should work as well, but it's easier to use find() if you are searching based on the primary key:

Query query = entityManager.createQuery(
    "SELECT m FROM MyEntity m WHERE id = :id");
query.setParameter("id", yourId);

MyEntity yourEntity = (MyEntity) query.getSingleResult();
查看更多
登录 后发表回答