Issue
Spring newbie here,
I want to test the the findById()
method of a repository, but it cannot find the entry even through it is saved (and exists) in the database:
@DataJpaTest
class CustomerRepoIntegration {
@Autowired
CustomerRepo customerRepo;
@Test
@Transactional
void findById() {
UUID uuid = UUID.randomUUID();
Customer customer = new Customer(uuid);
customerRepo.save(customer);
List<Customer> allCustomers = customerRepo.findAll();
assertEquals(1, allCustomers.size());
Optional<Customer> foundCustomer = customerRepo.findById(uuid);
assertTrue(foundCustomer.isPresent());
}
}
While the first assert is successful the second fails with:
Error: Failures:
Error: CustomerRepoIntegration.findById:32 expected: <true> but was: <false>
The rest of the code:
// CustomerRepo.java
public interface CustomerRepo extends JpaRepository<Customer, UUID> {}
// Customer.java
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Customer implements Serializable {
@Id
@GeneratedValue(generator = "UUID")
@GenericGenerator(
name = "UUID",
strategy = "org.hibernate.id.UUIDGenerator"
)
private UUID id;
}
I also made a reproduction repo here: https://github.com/ofhouse/stackoverflow-65818312
Solution
Try to use
customerRepo.saveAndFlush(customer)
instead save(customer)
Moreover, if you have configured an entity annotation responsible for auto-generating the id, the better idea would be not interfering in this mechanism creating your own UUID and initialize the entity. Hibernate will do it automatically for you.
Why not?
Hibernate has its own mechanism depends on the marked field with @Id
annotation whether to merge or persist entity with EntityManager (If the field is null or contains data).
Instead of
UUID uuid = UUID.randomUUID();
Customer customer = new Customer(uuid);
You can simply do
Customer customer = new Customer();
And fetch UUID from a persisted instance of entity here:
var persistedCustomer = customerRepo.saveAndFlush(customer);
...
Optional<Customer> foundCustomer = customerRepo.findById(persistedCustomer.uuid);
Answered By - centrumek
Answer Checked By - Marilyn (JavaFixing Volunteer)