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

我对 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

}

我缺少什么?


互换的青春
浏览 82回答 1
1回答

宝慕林4294392

由于一级缓存的概念,您创建并保存的初始对象与您加载的对象是同一个实例。由于您没有将创建的请求实体添加到内存模型中,而只是将其保存到数据库中,因此内存模型中不存在关系。为了获得所需的结果,您需要清除保存和重新加载之间的持久性上下文。@Test&nbsp; &nbsp; public void createStreamWithSeveralStreamTargetsAndDeleteStream() {&nbsp; &nbsp; &nbsp; &nbsp; List<StreamEntity> streamEntities = createStream(1);&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; List<RequestEntity> requestEntitySave = createRequest(1, streamEntityCheck);&nbsp; &nbsp; &nbsp; &nbsp; assertEquals(1, requestEntitySave.size());&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; //you need to clear the persistence context here&nbsp; &nbsp; &nbsp; &nbsp; //now a db query should execute.&nbsp; &nbsp; &nbsp; &nbsp; //Inject the entitymanager to your test @PersistenceContext EntityManager em;&nbsp; &nbsp; &nbsp; &nbsp; em.clear();&nbsp; &nbsp; &nbsp; &nbsp; List<StreamEntity> streamEntities = streamDao.findAll();&nbsp; &nbsp; &nbsp; &nbsp; assertEquals(1, streamEntities.size());&nbsp; &nbsp; &nbsp; &nbsp; StreamEntity streamEntity2 = streamEntities.get(0);&nbsp; &nbsp; &nbsp; &nbsp; streamEntity2.getRequestEntities(); - this collection shows 0&nbsp; &nbsp;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java