-3
我有一些問題與Hibernate延遲加載。見下面我的實體: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()方法調用,休眠初始化集合...
@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.爲什麼會出現這種情況?也許它有其他設置?
好吧,如果你提到的(形容)當您使用清楚發生了什麼'FetchType.LAZY'(或'FetchType.EAGER'),你期望那麼它是什麼,可能是有人來回答這個問題。只有使用您發佈的代碼片段才肯定不清楚。 – Lion
對不起,如果我的問題還不夠清楚的理解。我使用LAZY獲取類型,但是當我調用一些方法來回收我的實體時,我的實體中的所有字段都已初始化。我的情況下,當我調用「getById」方法,然後我得到IDiagnosis實體的「anamneses」集合已經初始化,就像我使用EAGER獲取類型。 Sory爲我的英語不好,我不是母語的人。 – dmgcodevil