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 を使用しています。これはなぜですか? 多分それは追加設定がありますか?