我对 Hibernate 很陌生,我已经在父对象和子对象之间设置了 @OneToMany 双向关系,并期望当我将所有内容保留在数据库中时,将父对象设置为子对象(因为子对象是关系的所有者)当我使用 ORM 获取父对象时,我希望也获取子对象,但作为回报,我看到零个子对象。
据我在互联网上阅读的内容了解,当我将子对象保留为与父对象的关系的所有者时,完整的 ORM 应该发挥根据预定义关系映射连接两个对象的魔力。此信息正确吗?
@Entity
@Table(name = "stream")
@SequenceGenerator(name = "sequence", sequenceName = "stream_id", allocationSize = 1)
public class StreamEntity extends EntityWithId {
// @MappedSuperclass with ID
@Column(name = "request_id")
@OneToMany(
mappedBy = "streamEntity",
fetch = FetchType.LAZY
)
private List<RequestEntity> requestEntities = new ArrayList<>();
// getters setters
}
@Entity
@Table(name = "request")
@SequenceGenerator(name = "sequence", sequenceName = "request_id", allocationSize = 1, initialValue = 1)
public class RequestEntity extends EntityWithId {
// @MappedSuperclass with ID
@JoinColumn(name = "stream_id")
@ManyToOne(fetch = FetchType.LAZY)
private StreamEntity streamEntity;
// getters setters
}
一些测试:
@Test
public void createStreamWithSeveralStreamTargetsAndDeleteStream() {
List<StreamEntity> streamEntities = createStream(1); // stream object is persisted here
List<RequestEntity> requestEntitySave = createRequest(1, streamEntityCheck);
assertEquals(1, requestEntitySave.size()); // request entity is persisted with the stream object into the database
List<StreamEntity> streamEntities = streamDao.findAll();
assertEquals(1, streamEntities.size());
StreamEntity streamEntity2 = streamEntities.get(0);
streamEntity2.getRequestEntities(); - this collection shows 0
}
我缺少什么?
宝慕林4294392
相关分类