JPA EntityNotFoundException。如何使用 JPA Criteria 查询在不考虑关系映射的情况下进行查询
我有一个产品实体。一种产品可以是另一种产品的子产品。该关系使用 OneToMany 进行映射,如下所示。
@OneToMany(mappedBy = "parentProd")
private Set<Products> childProd = new HashSet<>();
@ManyToOne
@JsonIgnoreProperties("childProd")
private Products parentProd;
从此映射生成的 parent_product_id 列以某种方式包含无效的parent_ids。因此,当我尝试使用 JPA 标准查询查询所有产品时,出现以下错误。
javax.persistence.EntityNotFoundException:无法找到 id 为 101 的 com.test.Products 在 org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$JpaEntityNotFoundDelegate.handleEntityNotFound(EntityManagerFactoryBuilderImpl.java:162) 在 org.hibernate.event.internal.DefaultLoadEventListener.load(DefaultLoadEventListener.java:234)
如何编写条件查询来选择所有 Product 实体而不考虑parent_child 关系?
@Entity
@Table(name = "products")
public class Products implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "productName")
private String productName;
@OneToMany(mappedBy = "parentProd")
private Set<Products> childProd = new HashSet<>();
@ManyToOne
@JsonIgnoreProperties("childProd")
private Products parentProd;
//Getters And Setters
}
I have a Product entity. One product can be a child of another. The relationship is mapped with OneToMany as follows.
@OneToMany(mappedBy = "parentProd")
private Set<Products> childProd = new HashSet<>();
@ManyToOne
@JsonIgnoreProperties("childProd")
private Products parentProd;
The parent_product_id column generated from this mapping somehow contains invalid parent_ids. Hence I am getting the following error when i try to query all products using JPA criteria query.
javax.persistence.EntityNotFoundException: Unable to find com.test.Products with id 101
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$JpaEntityNotFoundDelegate.handleEntityNotFound(EntityManagerFactoryBuilderImpl.java:162)
at org.hibernate.event.internal.DefaultLoadEventListener.load(DefaultLoadEventListener.java:234)
How to write a criteria query to select all Product entities without considering the parent_child relation?
@Entity
@Table(name = "products")
public class Products implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "productName")
private String productName;
@OneToMany(mappedBy = "parentProd")
private Set<Products> childProd = new HashSet<>();
@ManyToOne
@JsonIgnoreProperties("childProd")
private Products parentProd;
//Getters And Setters
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
以这种方式更改 oneToMany 注释:
这里 fetch = FetchType.Lazy 意味着如果您不明确询问,则不会获取数据。
Change the oneToMany annotation this way:
Here fetch = FetchType.Lazy means that data will not be fetched if you don't ask it explicitly.