【问题标题】:JPA load child of child listJPA加载子列表的子项
【发布时间】:2017-12-01 10:29:24
【问题描述】:

使用 spring boot 和 hibernate,假设我有一个 UserEntity 和一个孩子 TrailEntity 列表:

@Entity
@Table(name = "USER")
public class UserEntity {
  @OneToMany(cascade=CascadeType.ALL)
  @LazyCollection(LazyCollectionOption.FALSE)
  @JoinColumn(name="userID")
  private List<TrailEntity> trails = new ArrayList<>();
}

当我添加一个新的TrailEntity 并保存时,它可以正常工作并且UserEntity.trails 包含新的TrailEntity 对象。

userEntity.getTrails().add(trailEntity);
userService.save(userEntity);

但是,孩子中还有另一个列表已保存但未加载:

@Entity
@Table(name = "TRAIL")
public class TrailEntity {
  @OneToMany(cascade=CascadeType.ALL)
  @LazyCollection(LazyCollectionOption.FALSE)
  @JoinColumn(name="TrailID")
  private List<ImageEntity> images = new ArrayList<>();
}

当我这样做时:

userEntity.getTrails(0).getImages().add(imageEntity);
userService.save(userEntity);
userEntity = userService.findByUsername(USERNAME);

userEntity.getTrails(0).getImages().size() 为 0。

即链接到TrailEntityImageEntity 对象已保存,但有没有办法通过JPA(休眠)中的层次结构一直向下加载?

【问题讨论】:

  • 你能显示你正在进行保存等的事务吗?
  • 谢谢,您的评论提醒我打开 sql 日志记录,它显示 ImageEntity 正在保存。问题实际上是它没有加载它们,相应地改变了问题

标签: hibernate jpa spring-boot spring-data-jpa


【解决方案1】:

原来是ImageEntity中的另一个实体:

@Entity
@Table(name = "IMAGE")
public class ImageEntity {
  @ManyToOne(fetch = FetchType.EAGER)
  @JoinColumn(name="BeaconID", nullable=false)
  private BeaconEntity beaconEntity;
}

但它从未使用过,并且由于nullable=false 导致关联的ImageEntity 对象无法从数据库中加载。

ImageEntity.beaconEntity 删除nullable=false(默认为true)解决了问题

【讨论】:

    猜你喜欢
    • 2013-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-28
    • 2011-05-21
    • 2019-01-19
    • 2011-09-25
    相关资源
    最近更新 更多