gpt4 book ai didi

hibernate - 无法使用 SpringBoot 延迟初始化角色集合

转载 作者:行者123 更新时间:2023-12-02 23:57:48 25 4
gpt4 key购买 nike

我有一个基本的 SpringBoot 2.0.3.RELEASE 应用程序,使用 Spring Initializer、JPA、嵌入式 Tomcat、Thymeleaf 模板引擎,并将这些依赖项打包为可执行 JAR 文件,这些依赖项位于 pom.xml 中。

我有一个名为 Company 的域对象:

@Entity
@Table(name="t_company")
public class Company implements Serializable {

/**
*
*/
private static final long serialVersionUID = 1L;

public Company() {
}



/**
* @param companyName
*/
public Company(String companyName) {
super();
this.name = companyName;
}



@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@NotEmpty
@Length(max = 100)
private String name;


@OneToMany(mappedBy = "company", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private Set<User> users = new HashSet<>();

..
}

存储库层:

public interface CompanyRepository extends CrudRepository<Company, Long> {

@Query("select co from Company co join co.users us where co = ?1")
Company companyUsers (Company company);

}

服务层:

@Service
@Transactional(readOnly = true)
public class CompanyService {

@Autowired
private CompanyRepository companyRepository;

public Company companyUsers (Company company) {
return companyRepository.companyUsers(company);
}

}

Junit 文件:

@Test
public void testCompanyUsers() throws Exception {

Iterable<Company> companies = companyService.findAll();
Company company = companies.iterator().next();

assertNotNull (company);

company = companyService.companyUsers(company);
assertTrue (((Collection<?>) company.getUsers()).size() > 0);
}

但是当我运行测试时,我收到此错误:

failed to lazily initialize a collection of role: com.cor.backend.persistence.domain.backend.Company.users, could not initialize proxy - no Session

最佳答案

请仔细阅读我的一篇文章:https://arnoldgalovics.com/lazyinitializationexception-demystified/

您的主要问题是您试图访问事务之外的实体引用。您在这里有多种选择:

  • 在同一逻辑事务中获取必要的数据
  • 在 JPQL 查询中使用 FETCH JOIN
  • 使用预测

有关预测的更多阅读:https://arnoldgalovics.com/using-projections-in-your-data-access-layer/

此外,请考虑使用投影对性能的影响:https://arnoldgalovics.com/how-much-projections-can-help/

关于hibernate - 无法使用 SpringBoot 延迟初始化角色集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51876991/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com