User Repository
Take a closer look at the UserRepository interface and extended classes.
We'll cover the following...
The UserRepository class
Next to User and UserId, the Maven plugin also generated:
UserRepositoryUserRepositoryCustomUserRepositoryImpl
This is what UserRepository looks like:
package com.tamingthymeleaf.application.user;import org.springframework.data.repository.CrudRepository;import org.springframework.transaction.annotation.Transactional;@Transactional(readOnly = true)public interface UserRepository extends CrudRepository<User, UserId>,UserRepositoryCustom {}
This is just an interface that extends from the Spring Data JPA interface CrudRepository using our User and UserId as generics arguments.
If we want the database to generate primary keys upon saving the entity, we only need this interface. However, we want the repository to generate a unique id. For this purpose, we need a
UserRepositoryCustom interface:
package com.tamingthymeleaf.application.user;public interface UserRepositoryCustom {UserId nextId();}
That interface is implemented in UserRepositoryImpl:
package com.tamingthymeleaf.application.user;import io.github.wimdeblauwe.jpearl.UniqueIdGenerator;import java.util.UUID;public class UserRepositoryImpl implements UserRepositoryCustom {private final UniqueIdGenerator<UUID> generator;public UserRepositoryImpl(UniqueIdGenerator<UUID> generator) { //<.>this.generator = generator;}@Overridepublic UserId nextId() {return new UserId(generator.getNextUniqueId()); //<.>}}
- Inject a
UniqueIdGenerator<UUID>. This object is a Spring bean that will be responsible for generating uniqueUUIDobjects. JPearl has theInMemoryUniqueIdGeneratorclass that can do this for UUIDs. If you want to use Long objects instead, you’ll need to write your own implementation. - Use the
UniqueIdGeneratorto get a new uniqueidand create aUserIdinstance.
At runtime, Spring Data JPA will combine their implementation of the CrudRepository with our custom Java code from UserRepositoryImpl. Thus, if we inject the UserRepository interface into another object, that object can use the methods ...