我有一个基本的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);
}
但是当我运行测试时,出现了以下错误:
无法懒惰地初始化角色的集合:com.cor.backend.persistence.domain.backend.Company.users,无法初始化代理 - 没有会话