@ContextAdaptersAPIadaptersAPI;publicConnectiongetSQLConnection()throwsSQLException{// Create a connection object to the databaseJavaSQLApplicationapp=adaptersAPI.getJaxRsApplication(JavaSQLApplication.class);returnapp.dataSource.getConnection();}

ユーザーの作成

データベースに新規ユーザー・レコードを作成する場合に使用します。

@POSTpublicResponsecreateUser(@FormParam("userId")StringuserId,@FormParam("firstName")StringfirstName,@FormParam("lastName")StringlastName,@FormParam("password")Stringpassword)throwsSQLException{Connectioncon=getSQLConnection();PreparedStatementinsertUser=con.prepareStatement("INSERT INTO users (userId, firstName, lastName, password) VALUES (?,?,?,?)");try{insertUser.setString(1,userId);insertUser.setString(2,firstName);insertUser.setString(3,lastName);insertUser.setString(4,password);insertUser.executeUpdate();//Return a 200 OKreturnResponse.ok().build();}catch(SQLIntegrityConstraintViolationExceptionviolation){//Trying to create a user that already existsreturnResponse.status(Status.CONFLICT).entity(violation.getMessage()).build();}finally{//Close resources in all casesinsertUser.close();con.close();}}

ユーザーの取得

データベースからユーザーを取得します。

@GET@Produces("application/json")@Path("/{userId}")publicResponsegetUser(@PathParam("userId")StringuserId)throwsSQLException{Connectioncon=getSQLConnection();PreparedStatementgetUser=con.prepareStatement("SELECT * FROM users WHERE userId = ?");try{JSONObjectresult=newJSONObject();getUser.setString(1,userId);ResultSetdata=getUser.executeQuery();if(data.first()){result.put("userId",data.getString("userId"));result.put("firstName",data.getString("firstName"));result.put("lastName",data.getString("lastName"));result.put("password",data.getString("password"));returnResponse.ok(result).build();}else{returnResponse.status(Status.NOT_FOUND).entity("User not found...").build();}}finally{//Close resources in all casesgetUser.close();con.close();}}

ユーザーの削除

データベースからユーザー・レコードを削除します。

@DELETE@Path("/{userId}")publicResponsedeleteUser(@PathParam("userId")StringuserId)throwsSQLException{Connectioncon=getSQLConnection();PreparedStatementgetUser=con.prepareStatement("SELECT * FROM users WHERE userId = ?");try{getUser.setString(1,userId);ResultSetdata=getUser.executeQuery();if(data.first()){PreparedStatementdeleteUser=con.prepareStatement("DELETE FROM users WHERE userId = ?");deleteUser.setString(1,userId);deleteUser.executeUpdate();deleteUser.close();returnResponse.ok().build();}else{returnResponse.status(Status.NOT_FOUND).entity("User not found...").build();}}finally{//Close resources in all casesgetUser.close();con.close();}}