gpt4 book ai didi

java - Hibernate 查找错误的主键

转载 作者:行者123 更新时间:2023-11-30 09:23:50 27 4
gpt4 key购买 nike

我的实体有两个外键,其中一个是主键。我读了JPA Wiki如果子项(采购)的主键与父项(文章)的主键相同,则建立@OneToOne 关系。

@SuppressWarnings("serial")
@Entity
public class Procurement implements Serializable {

@Id
@OneToOne
// the child's primary key is the same as the parent
@JoinColumn(name = "articleId", referencedColumnName = "id")
private Article article;

@OneToOne
@JoinColumn(name = "supplierId", referencedColumnName = "id")
private Supplier supplier;

按照标准方法,JpaRepository 应该如下所示:

@Repository
public interface IProcurementRepository extends
JpaRepository<Procurement, Article>

但是,如果我想调用 findOne 方法(查找主键)传递“文章”对象,Hibernate 会抛出异常。

org.hibernate.TypeMismatchException: Provided id of the wrong type for class de.willms.spring.myerp.model.Procurement. Expected: class de.willms.spring.myerp.model.Procurement, got class de.willms.spring.myerp.model.Article

数据库表结构:

表“文章”(ID,短文本)

表“供应商”(ID,名称)

表“采购”(articleID、supplierID、price)

我必须更改什么才能通过相应的“文章”对象找到“采购”记录?

最佳答案

最后,我在 Hibernate 中找到了一个特殊的功能(令人惊奇,但在文档中很难理解)导致解决方案。

一旦主键由多个列组成,或者像我的情况一样,与其他表相关,就必须编写一个特殊的 ID 类。

@Embeddable    
public class Procurement_ID implements Serializable {

/**
* This attribute establishes the 1:1 connection to a record in the
* "article" table. The column "articleId" is a foreign key to the column
* "id" in the {@link Article} entity. (Warning: This is Hibernate
* specific!)
*/
@OneToOne
@JoinColumn(name = "articleId", referencedColumnName = "id")
private Article article;

/**
* This attribute establishes the 1:1 connection to a record in the table
* "supplier". The column "supplierId" is a foreign key to the column "id"
* in the {@link Supplier} entity. (Warning: This is Hibernate specific!)
*/
@OneToOne
@JoinColumn(name = "supplierId", referencedColumnName = "id")
private Supplier supplier;

(由于更“规范化”的数据模型,我切换到复合主键。)

由于@Embeddable注解,这个ID可以注入(inject)实体类。

@Entity
public class Procurement implements Serializable {

/**
* The composite primary key of the underlying table is defined in the
* {@link Procurement_ID} class.
*/
@EmbeddedId
private Procurement_ID procid;

在我使用这种方法的情况下,Hibernate 会插入一 strip 有正外键检查的新记录:

[DEBUG] Generated identifier: component[article,supplier]{article=de.willms.spring.myerp.model.Article#1, supplier=de.willms.spring.myerp.model.Supplier#1}, using strategy: org.hibernate.id.CompositeNestedGeneratedValueGenerator

... (Flusing) ...

[DEBUG] Listing entities: ... de.willms.spring.myerp.model.Procurement{price=2.5, deliveryTime=10, procid=component[article,supplier]{article=de.willms.spring.myerp.model.Article#1, supplier=de.willms.spring.myerp.model.Supplier#1}, priceUnit=$}

但是,遗憾的是 JpaRepository 无法注入(inject)仅涉及主键一部分的 find() 方法 stub 。它是“无法根据路径解析属性”。欢迎大家评论!

关于java - Hibernate 查找错误的主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15897354/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com