Writing a GET function for a read operation 

Now let's retrieve the organization using the GET function. We will start by defining a resource to accept a path parameter, which is orgId in this example.

The retrieveOrganization()  function in controller can be written to accept a path parameter, which happens to be an orgId that was returned when the identity was created. The retrieveOrganization() function returns the org object that is wrapped in a standard response in the JSON format, as seen in the following code:

@Path("/{orgId}")
@GET
@Produces(MediaType.APPLICATION_JSON)
fun retrieveOrganization(@PathParam("orgId") orgId: String): Response {
var organizationResponse: OrganizationResponse =
organizationService.retrieveOrganization(orgId)
return Response.status(200)
.entity(organizationResponse)
.build()
}

The service class function takes orgId and passes the request to dao layer, as seen in the following code:

fun retrieveOrganization(orgId: String): OrganizationResponse {
var organizationEntity: OrganizationEntity =
organizationDao.retrieveOrganization(orgId)

var organizationResponse: OrganizationResponse =
OrganizationResponse()
organizationResponse.orgId = organizationEntity.orgId
organizationResponse.orgName = organizationEntity.orgName
organizationResponse.description = organizationEntity.description
return organizationResponse
}

Once we get the response from the database after invoking the retrieveOrganization() function on the organizationDao instance, we map the entity object to the response class. The response class is similar to a request, but it is used for returning the response from the server side. The OrganizationResponse class is as follows:

class OrganizationResponse {
var orgId: String?= null
var orgName: String? = null
var description: String? = null

override fun toString(): String {
return "Organization [orgId=$orgId, orgName=$orgName,
description=$description]"
}
}

The  retrieveOrganization() function implementation in dao layer is as follows:

fun retrieveOrganization(orgId: String): OrganizationEntity {
entityManager.transaction.begin()
var organizationEntity: OrganizationEntity =
entityManager.find(OrganizationEntity::class.java, orgId)
entityManager.transaction.commit()
return organizationEntity
}

This uses the  find() function to retrieve the desired entity given the unique identifier, which is orgId, and returns the OrganizationEntity that is being loaded from the database.

So, we created a get organization API. Now, once again, build and deploy this RESTful service on the Tomcat Server.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset