Queries

In the previous section, we discussed how to persist the data to the database using the entity and the entity manager of the JPA. We can also retrieve the data from the database. JPA provides APIs to query the data from the database.

Let's say we want to retrieve the person data that we created and persisted. We could either use CreateNativeQueries, where we can just specify the query using SQL, or we can define a NamedQuery. This is a database query with a specific query syntax and is defined in the entity.

The named queries can be defined as constants and used in the entity class. For example, consider the following code:

const val FIND_ALL_PERSON: String = "Person.findAll"

@Table
@Entity
@NamedQuery(name = FIND_ALL_PERSON, query = "select p from Person p")
class Person : Identity() {
@Id
lateinit var identifier: UUID
lateinit var name: PersonName
lateinit var loginId: String
lateinit var address: Address
var preferredLanguage: PreferredLanguage? = null
}

We have defined NamedQuery in the Person entity. It takes a name, a unique constant defined in the class, and a query, which is JPQL. Person mentioned in the query is an entity type, not the table name.

We write all the constants in the Queries class and access that constant in the Person entity:

object Queries{
const val FIND_ALL_PERSON:String = "Person.findAll"
}

We can then use NamedQuery in our findAllPerson() function:

@Stateless
class App {
@Inject
private lateinit var identityCreator: IdentityCreator
@PersistenceContext
private lateinit var entityManager: EntityManager

fun createPerson(inputData: InputData): Person {
val person = identityCreator.createPerson(inputData)
entityManager.persist(person)
return person
}

fun findAllPerson(): List<Identity> {
return entityManager.createNamedQuery(Queries.FIND_ALL_PERSON,
Person::class.java).resultList
}
}

In the preceding class, we inject the required dependencies. We have two functions—createPerson() and findAllPerson(). We create a request instance of the InputData type and we insert the data using the entity manager. In the findAllperson() function, we use NamedQueries to retrieve the result and we get the resultList back using entityManager. This is a list of person entities that are persisted. This is how we retrieve the list and create the person record in the database.

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

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