我的实体
@Entity
@Table(name = "CATEGORY")
public class Category extends BaseEntity {
@ManyToOne(optional = true)
@JoinColumn(name = "PARENT_PK")
private Category parent;
@OneToMany(mappedBy = "parent")
private Set<Category> children = new HashSet<Category>();
}
@Test
final Category category = new Category();
category.setPk("4321");
categoryRepository.save(category);
final Category category1 = new Category();
category1.setPk("1234");
category1.setChildren(Collections.singleton(category));
final Category savedCategory1 = categoryRepository.save(category1);
直到现在一切看起来还不错,但是当我在test
中的下一行做如下
final Category savedCategory2 = categoryRepository.getOne(savedCategory1.getPk());
我在eclipse debug com.sun.jdi.InvocationException occurred invoking method.
中看到
而且测试栈跟踪说
org.hibernate.LazyInitializationException: could not initialize proxy - no Session
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:165)
我正在使用默认的spring boot,hibernate和h2设置,我没有关于数据源或实体管理器的配置。
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
@Transactional
@Repository
public interface CategoryRepository extends BaseRepository<Category, String>{
}
@NoRepositoryBean
public interface BaseRepository<T, PK extends Serializable> extends JpaRepository<T, PK> {
}