User Repository

Take a closer look at the UserRepository interface and extended classes.

The UserRepository class

Next to User and UserId, the Maven plugin also generated:

  • UserRepository
  • UserRepositoryCustom
  • UserRepositoryImpl

This is what UserRepository looks like:

Press + to interact
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:

Press + to interact
package com.tamingthymeleaf.application.user;
public interface UserRepositoryCustom {
UserId nextId();
}

That interface is implemented in UserRepositoryImpl:

Press + to interact
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;
}
@Override
public UserId nextId() {
return new UserId(generator.getNextUniqueId()); //<.>
}
}
  • Inject a UniqueIdGenerator<UUID>. This object is a Spring bean that will be responsible for generating unique UUID objects. JPearl has the InMemoryUniqueIdGenerator class that can do this for UUIDs. If you want to use Long objects instead, you’ll need to write your own implementation.
  • Use the UniqueIdGenerator to get a new unique id and create a UserId instance.

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 ...