简体   繁体   English

在Firebase数据库中存储现有POJO对象的最佳实践

[英]Best practice to store an existing POJO object in a Firebase database

In my app a user logs in. First I authenticate the user on the mail-address. 在我的应用程序中,用户登录。首先,我在邮件地址上对用户进行身份验证。

protected Boolean doAuthenticateWithEmail(final String mEmail, String mPassword)

In the callback method onAuthenticated the user is stored in the Firebase database with the following POJO: 在回调方法onAuthenticated中,用户使用以下POJO存储在Firebase数据库中:

public class User {

private String emailAddress;
private String profitNumber;
private String userName;

public User() {
    //Default constructor used by Firebase
}

public User(String emailAddress, String profitNumber, String userName) {
    this.emailAddress = emailAddress;
    this.profitNumber = profitNumber;
    this.userName = userName;
}

public String getEmailAddress() {
    return emailAddress;
}

public String getProfitNumber() {
    return profitNumber;
}

public String getUserName() {
    return userName;
}}

This is the code to store the userobject under a node that represents the mail-address. 这是将用户对象存储在代表邮件地址的节点下的代码。

Firebase userRef = new Firebase(Constants.FIREBASE_URL_USERS);
userRef.setValue(user.getEmailAddress().replace(".",","));
Firebase mailRef = userRef.child(user.getEmailAddress().replace(".",","));
mailRef.setValue(user);

My question is: What is the best practice if this user already exists? 我的问题是:如果此用户已经存在,最佳实践是什么? Should I first check if the data exists or just overwrite the existing data. 我应该先检查数据是否存在,还是只覆盖现有数据。

It turns out that a check is necessary. 事实证明,检查是必要的。

     /**
     * Encode user email replacing "." with "," to be able to use it
     * as a Firebase db key
     */
    String mEncodedEmail = mEmail.replace(".", ",");

    /* If the user doesn't exists, make a user */
    final Firebase userLocation = new Firebase(Constants.FIREBASE_URL_USERS).child(mEncodedEmail);
    userLocation.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
                /* If nothing is there ...*/
            if (dataSnapshot.getValue() == null) {

                userLocation.setValue(user);
            }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM