为什么在@Transactional中发生lazyInitializationException?

时间:2019-06-19 10:37:49

标签: java spring hibernate spring-boot

我必须具有以下实体:

public class FeatureType {
   @Id Sring id;
   ...
   @OneToMany(mappedBy="featureType", fetch=FetchType.LAZY)
   List<Metadata> entities = new ArrayList();
}

public class Metadata{
   ...
   @ManyToOne
   FeatureType featureType;
}

现在,featureType存储库如下:

@Repository
public interface FeatureTypeRepository extends JpaRepository<FeatureType, String> 
{}

我创建了一个字符串到FeatureType转换器,如下所示:

class StringToFeatureType implement Converter<String, FeatureType>
{
   private FeatureTypeRepsitory rep;
   public StringToFeatureType(FeatureTypeRepsitory rep){this.rep = rep;}
   @Override
   public FeatureType convert(String name)
   {
       return rep.findByIdOrNull(name);
   }
}

我的控制器有问题

@RestController
public FeatureTypeController()
{
   @Transactional
   @GetMapping("/featureType-{featureType}/metadata")
   List<Metadata> getMetadata(FeatureType featureType)
   {
      system.out.println(entityManager.contains(featureType));//print false
      system.out.println(featureType.getMetadata().size());//Occur Error here
      return featureType.getMetadata();
   }
}

我已经打开事务,但是当程序接收到行system.out.println(featureType.getMetadata().size());时,发生如下异常:

  

org.hibernate.LazyInitializationException:无法延迟初始化   角色集合:fava.FeatureType.metadata,无法初始化   代理-没有会话

我知道featurType是否具有一些元数据,问题发生在序列化中,但是在行system.out.println(featureType.getMetadata().size())处出现了错误。什么问题?

0 个答案:

没有答案