Jan*_*nar 5 spring-data-jpa spring-boot
我在测试 Spring DataJpaTest 中是否加载了集合时遇到了麻烦。
为此,我创建了一个具有 id 和项目列表的实体,如下所示。该列表应该是延迟加载的(所以我假设它不应该在测试中加载)。
@Data
@Entity
@Table(name = "examples")
public class Example {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
protected Long id;
@OneToMany(mappedBy = "example", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<ExampleElement> collection;
}
Run Code Online (Sandbox Code Playgroud)
存储库代码如下所示:
@Repository
public interface ExampleRepository extends PagingAndSortingRepository<Example, Long> {
@Query("SELECT e FROM Example e")
List<Example> findAllActive();
}
Run Code Online (Sandbox Code Playgroud)
在测试中,我正在创建一个新的 Example 实体,生成集合,将实体保存到数据库,然后从数据库中获取实体并检查集合是否已初始化。测试代码如下所示:
@RunWith(SpringRunner.class)
@DataJpaTest
@AutoConfigureTestDatabase(replace = Replace.NONE)
public class ExampleRepositoryTest {
@Autowired
private ExampleRepository repository;
@Test
public void myTest() {
Example example = new Example();
example.setCollection(Utils.generateCollection()))
repository.save(example);
List<Example> actives = repository.findAllActive();
// tests in a loop whether the collection is initialized which should return false
}
Run Code Online (Sandbox Code Playgroud)
我尝试了以下方法:
em.getEntityManager().getEntityManagerFactory().getPersistenceUnitUtil()和调用isLoaded(actives.get(0).getCollection())和isLoaded(actives.get(0), "collection")方法从那里获取 PersistenceUnitUtil - 都返回 trueHibernate.isInitialized(actives.get(0).getCollection())和Hibernate.isPropertyInitialized(actives.get(0), "collection")方法,它们都返回 true。我错过了什么?
| 归档时间: |
|
| 查看次数: |
339 次 |
| 最近记录: |