Spring Data JPA has is the ability to create repository implementations automatically, at runtime, from a repository interface. We will see how this works by creating a repository to access the User entities. Create a repositories package and include UserRepository.kt in it:
package com.example.messenger.api.repositories
import com.example.messenger.api.models.User
import org.springframework.data.repository.CrudRepository
interface UserRepository : CrudRepository<User, Long> {
fun findByUsername(username: String): User?
fun findByPhoneNumber(phoneNumber: String): User?
}
UserRepository extends the CrudRepository interface. The entity type and id type it works with are specified in the generic parameters of CrudRepository. By extending CrudRepository, UserRepository inherits methods for working with User persistence, such as methods for saving, finding, and deleting User entities.
In addition, Spring JPA allows the declaration of other query functions by the use of method signatures. We exploited this capability to create findByUsername() and findByPhoneNumber() functions.
As we currently have three entities, we need to have three repositories to query them. Create a MessageRepository interface in repositories:
package com.example.messenger.api.repositories
import com.example.messenger.api.models.Message
import org.springframework.data.repository.CrudRepository
interface MessageRepository : CrudRepository<Message, Long> {
fun findByConversationId(conversationId: Long): List<Message>
}
Notice the preceding method signature specifies List<Message> as its return type. Spring JPA automatically recognizes this and returns a list of Message elements when findByConversationId() is called.
Lastly, implement a ConversationRepository interface:
package com.example.messenger.api.repositories
import com.example.messenger.api.models.Conversation
import org.springframework.data.repository.CrudRepository
interface ConversationRepository : CrudRepository<Conversation, Long> {
fun findBySenderId(id: Long): List<Conversation>
fun findByRecipientId(id: Long): List<Conversation>
fun findBySenderIdAndRecipientId(senderId: Long,
recipientId: Long): Conversation?
}
As we now have our entities set and the necessary repositories to query these entities, we can start work on implementing the business logic of the messenger backend. This will require us to learn about services and service implementations.