因此,这可能是一个愚蠢的问题,但是何时使用以下方法注册课程:
ObjectifyService.register( User.class );
当前,我正在类似接口的类的构造函数中执行此操作,该类在其他类中用于简化数据存储对我的应用程序的使用。但是,我收到此错误:
尝试两次注册种类“用户”
所以,我想我的问题是,您多久在一次Objective中注册类?
谢谢!
PS这是我的整个课程:
import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.Iterator; import javax.crypto.BadPaddingException; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.persistence.Id; import com.googlecode.objectify.Objectify; import com.googlecode.objectify.ObjectifyService; import com.googlecode.objectify.annotation.Indexed; import com.googlecode.objectify.annotation.Unindexed; public class UsersService { Objectify ojy; public UsersService(){ ObjectifyService.register( User.class ); ojy = ObjectifyService.begin(); } public void regUser(String email, String password, String firstName, String lastName){ //TODO: Check syntax if email //TODO: store encrypted password } public void regUser(String email, String password, String firstName){ regUser(email, password, firstName, null); } public void regUser(String email, String password){ regUser(email, password, "", ""); } public boolean checkFor(Long acc_id){ User checked_user = ojy.find(User.class, acc_id); if(checked_user == null){ return false; }else{ return true; } } public User getUser(String email, String password) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException{ String pass_enc = MyUtils.getEncrypted(password); Iterable<User> users = ojy.query(User.class).filter("email", email).filter("password", pass_enc); Iterator<User> iter = users.iterator(); if(iter.hasNext()){ return iter.next(); }else{ return null; } } }
更新资料
这是最佳实践解决方案:
使用您自己的服务,这可以确保在使用Objectify之前已注册您的实体,但对于未访问数据存储区的请求,并不一定会影响应用程序的启动。
import com.googlecode.objectify.Objectify; import com.googlecode.objectify.ObjectifyFactory; import com.googlecode.objectify.ObjectifyService; public class OfyService { static { ObjectifyService.register(User.class); } public static Objectify ofy() { return ObjectifyService.begin();//prior to v.4.0 use .begin() , //since v.4.0 use ObjectifyService.ofy(); } public static ObjectifyFactory factory() { return ObjectifyService.factory(); } }
然后像这样使用它:
public User createUser(User pUser) { Objectify objectify = OfyService.ofy(); objectify.put(pUser); return pUser; }
原始答案(最好使用上面的代码):
您应该在您的类中以这种方式进行操作,只需将如下所示的静态块放入:
static{ ObjectifyService.register( User.class ); }
ps,您也看一下对象化的最佳实践
http://code.google.com/p/objectify- appengine/wiki/BestPractices