根据ID以外的属性获取实体

谢里丹·格雷

我是Endpoints的新手,正在尝试通过id以外的属性查询Entity。具体来说,我有一个User.java和UserEndpoints.java类,并且希望能够基于'email'属性返回一条记录。当我传递特定记录的ID时,我能够得到返回到Activity的结果,该Activity调用异步任务,因此我知道数据可以正常运行。我是否需要创建一个名为getUserByEmail之类的终结点?我是否需要以某种方式修改getUser函数?

UserEndpoint.java

@Api(name = "userendpoint")
public class UserEndpoint {
/**
 * This method lists all the entities inserted in datastore. It uses HTTP
 * GET method and paging support.
 * 
 * @return A CollectionResponse class containing the list of all entities
 *         persisted and a cursor to the next page.
 */
@SuppressWarnings({ "unchecked", "unused" })
@ApiMethod(name = "listUser")
public CollectionResponse<User> listUser(
        @Nullable @Named("cursor") String cursorString,
        @Nullable @Named("limit") Integer limit) {

    EntityManager mgr = null;
    Cursor cursor = null;
    List<User> execute = null;

    try {
        mgr = getEntityManager();
        Query query = mgr.createQuery("select from User as User");
        if (cursorString != null && cursorString != "") {
            cursor = Cursor.fromWebSafeString(cursorString);
            query.setHint(JPACursorHelper.CURSOR_HINT, cursor);
        }

        if (limit != null) {
            query.setFirstResult(0);
            query.setMaxResults(limit);
        }

        execute = (List<User>) query.getResultList();
        cursor = JPACursorHelper.getCursor(execute);
        if (cursor != null)
            cursorString = cursor.toWebSafeString();

        // Tight loop for fetching all entities from datastore and
        // accomodate
        // for lazy fetch.
        for (User obj : execute)
            ;
    } finally {
        mgr.close();
    }

    return CollectionResponse.<User> builder().setItems(execute)
            .setNextPageToken(cursorString).build();
}

/**
 * This method gets the entity having primary key id. It uses HTTP GET
 * method.
 * 
 * @param id
 *            the primary key of the java bean.
 * @return The entity with primary key id.
 */
@ApiMethod(name = "getUser")
public User getUser(@Named("id") Long id) {
    EntityManager mgr = getEntityManager();
    User user = null;
    try {
        user = mgr.find(User.class, id);
    } finally {
        mgr.close();
    }
    return user;
}

/**
 * This inserts a new entity into App Engine datastore. If the entity
 * already exists in the datastore, an exception is thrown. It uses HTTP
 * POST method.
 * 
 * @param user
 *            the entity to be inserted.
 * @return The inserted entity.
 */
@ApiMethod(name = "insertUser")
public User insertUser(User user) {
    EntityManager mgr = getEntityManager();
    try {
        if (containsUser(user)) {
            throw new EntityExistsException("Object already exists");
        }
        mgr.persist(user);
    } finally {
        mgr.close();
    }
    return user;
}

/**
 * This method is used for updating an existing entity. If the entity does
 * not exist in the datastore, an exception is thrown. It uses HTTP PUT
 * method.
 * 
 * @param user
 *            the entity to be updated.
 * @return The updated entity.
 */
@ApiMethod(name = "updateUser")
public User updateUser(User user) {
    EntityManager mgr = getEntityManager();
    try {
        if (!containsUser(user)) {
            throw new EntityNotFoundException("Object does not exist");
        }
        mgr.persist(user);
    } finally {
        mgr.close();
    }
    return user;
}

/**
 * This method removes the entity with primary key id. It uses HTTP DELETE
 * method.
 * 
 * @param id
 *            the primary key of the entity to be deleted.
 */
@ApiMethod(name = "removeUser")
public void removeUser(@Named("id") Long id) {
    EntityManager mgr = getEntityManager();
    try {
        User user = mgr.find(User.class, id);
        mgr.remove(user);
    } finally {
        mgr.close();
    }
}

private boolean containsUser(User user) {
    EntityManager mgr = getEntityManager();
    boolean contains = true;
    if (user.getKey() == null)
        return false;
    try {
        User item = mgr.find(User.class, user.getKey());
        if (item == null) {
            contains = false;
        }
    } finally {
        mgr.close();
    }
    return contains;
}

private static EntityManager getEntityManager() {
    return EMF.get().createEntityManager();
}
}

User.java

@Entity
public class User {
/*
 * Autogenerated primary key
 */
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Key key;
private String email;
private String password;
private String gender;
private Date birthdate;

public Key getKey() {
    return key;
}

public void setKey(Key key) {
    this.key = key;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

public String getGender() {
    return gender;
}

public void setGender(String gender) {
    this.gender = gender;
}

public Date getBirthdate() {
    return birthdate;
}

public void setBirthdate(Date birthdate) {
    this.birthdate = birthdate;
}
}
谢里丹·格雷

这就是我最终解决的方式:

/**
 * This method gets the first entity having email. It uses HTTP GET
 * method.
 * 
 * @param email
 *            
 * @return The entity with email.
 */
@ApiMethod(name = "getUserByEmail", path="getUserByEmail")
public User getUserByEmail(@Named("email") String email) {
    EntityManager mgr = getEntityManager();
    User user = null;
    try {
        //Query query = mgr.createQuery("SELECT u FROM User u WHERE u.email = '" + email + "'");
        Query query = mgr.createQuery("SELECT FROM User u WHERE u.email = :email");
        query.setParameter("email", email);
        user = (User) query.getSingleResult();
    } finally {
        mgr.close();
    }
    return user;
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

根据获取的属性对实体进行排序

来自分类Dev

核心数据:如何根据相关实体的属性获取实体

来自分类Dev

核心数据:如何根据相关实体的属性获取实体

来自分类Dev

根据特定属性的值获取元素的类或ID名称

来自分类Dev

根据子表中的某些属性过滤器获取父实体

来自分类Dev

dbpedia以英语以外的语言获取实体

来自分类Dev

获取继承实体的导航属性

来自分类Dev

获取继承实体的导航属性

来自分类Dev

仅获取实体的投影属性

来自分类Dev

CRM 9 - 使用 JavaScript WebResource 根据 ID 从 CRM 实体中获取记录

来自分类Dev

根据ID获取对象

来自分类Dev

JPQL根据孙子属性选择实体

来自分类Dev

在事务中获取实体的 id

来自分类Dev

如何根据 ASP.NET MVC 实体框架中的电子邮件地址获取用户的 ID

来自分类Dev

jQuery的获取'ID'属性

来自分类Dev

需要获取id属性

来自分类Dev

无法在实体框架中获取导航属性

来自分类Dev

处理关系属性时获取/设置实体

来自分类Dev

仅获取OData中实体的属性定义

来自分类Dev

插入后获取实体导航属性

来自分类Dev

实体框架从子属性获取SUM

来自分类Dev

获取核心数据相关实体属性

来自分类Dev

获取微风实体中存在的属性名称

来自分类Dev

处理关系属性时获取/设置实体

来自分类Dev

获取所有实体及其导航属性

来自分类Dev

无法在实体框架中获取导航属性

来自分类Dev

使用Id以外的属性查询DocumentDB

来自分类Dev

CakePHP显示ID以外的其他属性

来自分类Dev

根据属性id查找并获取XML节点的所有子节点