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

标签 hibernate spring-mvc spring-boot junit spring-data-jpa

我有一个基本的 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/

相关文章:

java - 手动重命名后文件重复

hibernate - c3p0.SQLWarnings 服务器用户 ID 29 不是数据库 'defaultdb' 中的有效用户

java - Spring Boot从服务类调用方法的问题

url - 让 Spring 告诉 FreeMarker 要使用的 URL 编码

java - 如何从 Azure Blob 获取所有文件并压缩它们?

java - 使用多个表单在 View 上提交表单时出现 Spring "Neither BindingResult nor plain target object for bean name"错误

mysql - hibernate 异常 : Errors in named queries: FindPostWithComments

java - Hibernate:启用 useAffectedRows 导致无操作更新的 OptimisticLockExceptions

java - @ExceptionHandler 不会捕获从 Spring Formatters 抛出的异常

html - Spring MVC - 如何在 bool 变量中绑定(bind) HTML 复选框值