我有数据库性能问题。
假设我的数据模型如下所示。
UserTable.java
@Id
@Column(name = "USER_ID", nullable = false)
private Long userId;
// other user fields
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
private Set<ProfilePhotoTable> photos = new HashSet<>();
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
private Set<AlbumPhotoTable> photos = new HashSet<>();
PhotoTable.java
@Id
@Column(name = "PHOTO_ID", nullable = false)
private Long photoId;
// other photo fields
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "USER_ID")
private UserTable user;
ProfilePhotoTable.java
@Entity
@Table(name = "PROFILEPHOTO")
@PrimaryKeyJoinColumn(name = "PROFILEPHOTO_ID", referencedColumnName = "PHOTO_ID")
public class ProfilePhotoTable extends PhotoTable
AlbumPhotoTable.java
@Entity
@Table(name = "ALBUMPHOTO")
@PrimaryKeyJoinColumn(name = "ALBUMPHOTO_ID", referencedColumnName = "PHOTO_ID")
public class ProfilePhotoTable extends PhotoTable
现在,假设我想编写一个查询,该查询将为用户获取所有照片-所有个人资料照片和所有相册照片。
但是,我不希望每次从数据库请求用户信息时都提取照片,这就是为什么我fetch = FetchType.LAZY
在照片字段中指定的原因。
基本上,我对这两种方法之间存在疑问。
有两个独立的查询,第一个独立的查询是UserTable
通过ID从数据库中获取,第二个是获取照片,类似SELECT * FROM Photo WHERE userId = :userId
。
一个查询,join fetch
该查询将为用户提供相应的照片。但是,我不确定该查询的进行方式,因为照片在“相册”和“个人资料”照片中分开。我在这篇文章中发现类似
评论= entityManager.createQuery(
“从PostComment pc中选择pc” +“加入pc.post” +“其中pc.review =:review”,PostComment.class).setParameter(“ review”,review).getResultList();
应该使用,但是我不确定如何将其应用于用例。
问题是,哪种方法在性能方面更好,如果是第二种,应该如何构造查询?
如果要使用JPA 2.1或更高版本,则要获取数据“ EAGER”或“ LAZY”,可以使用@NamedEntityGraph进行控制。
本文对此进行了很好的解释:https : //thoughts-on-java.org/jpa-21-entity-graph-part-1-named-entity/
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句