簡體   English   中英

根據ID以外的屬性獲取實體

[英]Get Entity by Attribute other than 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;
}
}

由於數據存儲區為您創建了單索引,因此應該可以執行以下操作

User user = mgr.findFirst(User.class, ,"email", email);

提示:如果您還想確保電子郵件是唯一的,並且對於用戶來說不會改變,則將其作為ID。

這就是我最終解決的方式:

/**
 * 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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM