我有两个实体:
public class UserAccount extends BaseEntity {
@Expose
@Property("username")
@Indexed(value = IndexDirection.ASC, name = "userNameIndex", unique = true)
private String userName = new String();
@Expose
@Property("password")
private String password = new String();
}
和
public class UserProfile extends BaseEntity {
@Expose
@Property("first name")
@Indexed(value = IndexDirection.ASC, name = "firstNameIndex")
private String firstName = new String();
@Expose
@Property("middle name")
// @Indexed(value = IndexDirection.ASC, name = "middleNameIndex")
private String middleName = new String();
@Expose
@Property("last name")
@Indexed(value = IndexDirection.ASC, name = "lastNameIndex")
private String lastName = new String();
@Expose
@Reference(/* idOnly = true, */value = "user id" /* , lazy = true */)
private UserAccount userAccount = new UserAccount();
}
我正在尝试根据搜索到的UserName(包含!但唯一)和UsedProfileObjectId(@Id)搜索所有用户。如果提供的用户名是唯一的,那么我正在尝试约束检查,同时保存userdetails? (我需要在新的添加和更新案例中检查它)。所以我试着编写这个代码:
public List<UserProfile> findAllUsersWithSameUserName(ObjectId id,
String userName) {
Datastore ds = getDatastore();
Query<UserProfile> profileQuery = ds.createQuery(UserProfile.class);
Query<UserAccount> accountQuery = ds.createQuery(UserAccount.class);
accountQuery.criteria("username").containsIgnoreCase(userName);
container.add(profileQuery.criteria("user id").in(
accountQuery.asKeyList()));
return profileQuery.asList();
}
但是这段代码正在显示
显示java.lang.NullPointerException
@Reference(value =&#34; user id&#34;,lazy = true) private UserAccount userAccount = new UserAccount();
但是,我不知道如何用无数据重新绑定这些对象?
我试着这样做:
user = userProfileDAO.findUserByProfileID(id);
user.getUserAccount();
user.getUserAccount().getUserName();
user.getUserAccount().getPassword();
// Gson gson = new Gson();
// .setDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz").create();
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd")
.excludeFieldsWithoutExposeAnnotation().setPrettyPrinting()
.create();
response = gson.toJson(user, UserProfile.class);
仍有响应 EMPTY UserAccount数据:
"userAccount": {
"userName": "",
"password": "",
"isDeleted": false,
"isActive": false,
"addedOn": "2015-08-06"
},
即使经过检查,我也可以获得这样的实际数据:user.getUserAccount().getUserName()
找不到在Morphia中使用lazy = true的任何好例子?如何对我的代码强制执行这种惰性效果?
答案 0 :(得分:1)
这是一种如何完成@Reference对象查询的方法:
public UserProfile findAllUsersWithSameUserName(ObjectId id, String userName) {
Datastore ds = getDatastore();
Query<UserProfile> profileQuery = ds.createQuery(UserProfile.class);
Query<UserAccount> accountQuery = ds.createQuery(UserAccount.class);
accountQuery.criteria("username").hasThisOne(userName.toString());
profileQuery.and(profileQuery.criteria("_id").notEqual(id),
profileQuery.criteria("user id").in(accountQuery.asKeyList()));
return profileQuery.get();
}