test jparepository findbyid为uuid返回null

q9rjltbz  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(398)

我是 Spring 新手,
我想测试一下 findById() 方法,但即使该条目已保存(并存在)在数据库中,也找不到该条目:

@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());
    }
}

当第一个Assert成功时,第二个Assert失败:

Error:  Failures: 
Error:    CustomerRepoIntegration.findById:32 expected: <true> but was: <false>

其余代码:

// 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;
}

我还在这里做了一个复制回购:https://github.com/ofhouse/stackoverflow-65818312

unhi4e5o

unhi4e5o1#

尝试使用 customerRepo.saveAndFlush(customer) 相反 save(customer) 此外,如果您已经配置了一个负责自动生成id的实体注解,那么更好的方法是不要干涉创建您自己的uuid和初始化实体的机制。hibernate会自动为您完成。
为什么不?
hibernate有自己的机制,它依赖于带有 @Id 注解是否将实体与entitymanager合并或持久化(如果字段为null或包含数据)。
而不是

UUID uuid = UUID.randomUUID();
Customer customer = new Customer(uuid);

你可以简单的做

Customer customer = new Customer();

从实体的持久化示例中获取uuid:

var persistedCustomer = customerRepo.saveAndFlush(customer);
...
Optional<Customer> foundCustomer = customerRepo.findById(persistedCustomer.uuid);

相关问题