我在使用Hibernate延迟加载方面遇到了一些问题。请参阅下面的实体:
@Entity
@Table(name = "diagnoses")
public class Diagnosis extends Domain implements IDiagnosis {
@Column(name = "short_name")
private String shortName;
@Column(name = "full_name")
private String fullName;
@Column(name = "code")
private int code;
@OneToMany(fetch = FetchType.LAZY, targetEntity = Anamnesis.class, cascade = CascadeType.ALL,
orphanRemoval = true)
@JoinColumn(name = "diagnoses_id", nullable = false)
private Set<IAnamnesis> anamneses = new HashSet<>();
@OneToMany(fetch = FetchType.LAZY, targetEntity = Complaint.class, cascade = CascadeType.ALL,
orphanRemoval = true)
@JoinColumn(name = "diagnoses_id", nullable = false)
private Set<IComplaint> complaints = new HashSet<>();
...
}
但是当我在测试中调用findAll()或findById()方法时,hibernate初始化集合......
@Service("diagnosisService")
public class DiagnosisService implements IDiagnosisService {
@Autowired
private IDiagnosisRepository diagnosisRepository;
@Override
@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public IDiagnosis getById(String id) {
return diagnosisRepository.findById(id);
}
@Override
@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public boolean saveOrUpdate(IDiagnosis diagnosis) {
boolean result = false;
if (diagnosis != null) {
if (StringUtils.isEmpty(diagnosis.getId())) {
diagnosisRepository.insert(diagnosis);
result = true;
} else {
diagnosisRepository.update(diagnosis);
result = true;
}
}
return result;
}
@Override
@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public boolean delete(IDiagnosis diagnosis) {
boolean deleted = false;
if (diagnosis != null) {
diagnosisRepository.delete(diagnosis);
deleted = true;
}
return deleted;
}
@Override
@Transactional(propagation = Propagation.REQUIRED, readOnly = true)
public List<IDiagnosis> getAll() {
return diagnosisRepository.findAll();
}
public class DiagnosisRepository{
...
public T findById(ID id) {
T t = null;
List<T> data = sessionFactory.getCurrentSession().createQuery(String.format("from %s where id='%s'",
getClassName(), id)).list();
if (CollectionUtils.isNotEmpty(data)) {
t = data.get(FIRST_ENTITY);
}
return t;
}
/**
* {@inheritDoc}
*/
@Override
public List<T> findAll() {
return sessionFactory.getCurrentSession().createQuery(String.format("from %s", getClassName())).list();
}
...
}
我使用Hibernate 4.为什么会这样?也许它有额外的设置?
答案 0 :(得分:1)
为什么你认为它已初始化?在调试时,您是否看到集合中的初始化字段设置为true?您是否尝试过在交易之外访问该集合。它应该通过LazyInitializationException。
默认情况下,btw Onetomany映射是惰性的。你无需明确提及它。