为了账号安全,请及时绑定邮箱和手机立即绑定

Spring-Data 中子对象不与父对象一起获取

Spring-Data 中子对象不与父对象一起获取

互换的青春 2023-09-06 14:52:22
我对 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}一些测试:@Testpublic 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}我缺少什么?
查看完整描述

1 回答

?
宝慕林4294392

TA贡献2021条经验 获得超8个赞

由于一级缓存的概念,您创建并保存的初始对象与您加载的对象是同一个实例。由于您没有将创建的请求实体添加到内存模型中,而只是将其保存到数据库中,因此内存模型中不存在关系。


为了获得所需的结果,您需要清除保存和重新加载之间的持久性上下文。


@Test

    public void createStreamWithSeveralStreamTargetsAndDeleteStream() {

        List<StreamEntity> streamEntities = createStream(1); 


        List<RequestEntity> requestEntitySave = createRequest(1, streamEntityCheck);

        assertEquals(1, requestEntitySave.size()); 


        //you need to clear the persistence context here

        //now a db query should execute.

        //Inject the entitymanager to your test @PersistenceContext EntityManager em;

        em.clear();


        List<StreamEntity> streamEntities = streamDao.findAll();

        assertEquals(1, streamEntities.size());

        StreamEntity streamEntity2 = streamEntities.get(0);

        streamEntity2.getRequestEntities(); - this collection shows 0


   }


查看完整回答
反对 回复 2023-09-06
  • 1 回答
  • 0 关注
  • 81 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信