2017-11-16 4 views
0

新しいユーザーはPOSTメソッドで作成され、その後、データベースにトークンを作成するために必要な一意のIDが添付されます。JavaサービスのPOST後にコンテンツを返すためのREST

トークンを作成する唯一の方法は、ユーザー作成のプロセスの後です。私はそれをデータベースから照会して、今はIDを持っているはずですが、それを行う方法はわかりません。

エンティティを作成した直後にデータベースからエンティティを取得する方法はありますか?この同様の質問を見たが、答えを見つけることができなかった場合は

Is it ok by REST to return content after POST?

@POST 
    @Consumes({MediaType.APPLICATION_JSON}) 
    public Response create(@QueryParam("email") String email, @QueryParam("username") String userName, @QueryParam("password") String password) { 
     if (TextUtil.isEmpty(userName) || TextUtil.isEmpty(password) || TextUtil.isEmpty(email)) { 
      return Response.status(Response.Status.BAD_REQUEST).build(); 
     } else { 
      User newUser = new User(); 
      newUser.setEmail(email); 
      newUser.setUsername(userName); 
      newUser.setPass(password); 
      super.create(newUser); //ths line create user in database 
      String id = newUser.getUid() + ""; //the newUser has no id yet so it is null but I want this id from database 
      return Response.status(Response.Status.OK).entity("id: " + id).build(); 
     } 
    } 

がsuper.method作成は

public void create(T entity) { 
     getEntityManager().persist(entity); 
    } 

私はこのチュートリアル https://netbeans.org/kb/docs/websvc/rest.html

+0

私は私の質問にedditedいる –

+0

をリストsuper.create()メソッドを追加してください:たぶん、あなたはより良いcreateメソッドを記述する必要があります。ありがとうございます – coinhndp

+0

'' ' super.create(newUser); super.getEntityManager()。flush(); super.getEntityManager()。find(User.class、newUser.getUId()) '' ' –

答えて

0
を使用してREST APIを生成します
getEntityManager().persist(entity); 

エンティティentity.setId(...)を呼び出して

+0

私はデータベース内でidをauto incrementを使用して設定しました。コードでIDを設定するにはどうすればよいですか?私はそれを手動で正しく設定することはできませんか? – coinhndp

0

私のコメント私はEntityManagerを同期する方法を示します。

public <T> T create(T t) throws Exception { 

     try { 
      entityManager.persist(t); 
      entityManager.flush(); 
     } catch (Exception e) { 
      throw e; 
     } finally { 
      entityManager.clear(); 
     } 

     return t; 
    } 

そして

newUser = super.create(newUser); 
+0

IDはデータベース内にのみ作成されているため、newUserにはIDはありません – coinhndp

+0

'entityManager.flush();'が呼び出されると、すべての変更がデータベースに書き込まれ、JPAで定義されたIDが生成されます。ユーザーのUIdフィールドをどのように生成しますか? –

+0

私はデータベース内で自動増分を使用してそれを生成します。 idがnullの場合、ユーザーのIDが自動的に生成されます。 IDを生成するにはどうすればよいですか?私は、 – coinhndp

関連する問題