此类未定义 IdClass 外键

Posted

技术标签:

【中文标题】此类未定义 IdClass 外键【英文标题】:This class does not define an IdClass foreign key 【发布时间】:2021-03-13 13:26:08 【问题描述】:

我在电话表中使用 productid 作为外键。我不知道在PhoneRepository 的id 部分写什么。因为报错

Product.java

@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Product 

@Id  @GeneratedValue(strategy = GenerationType.IDENTITY)
private long productID;
...

电话.java

@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
@IdClass(Product.class)
public class Phone implements Serializable


private static final long serialVersionUID = 1L;

@Id
@OneToOne
@JoinColumn(name = "productID")
private Product product;
...

PhoneRepository.java

 @Repository
 public interface PhoneRepository extends CrudRepository<Phone, Product>  //I tried Long

  

错误

Caused by: java.lang.IllegalArgumentException: This class [class 
com.test.project.data.entity.prod.Phone] does not define an IdClass

【问题讨论】:

这能回答你的问题吗? Spring JPA Composite key: This class does not define an IdClass 没有。我想这不是问题 我认为您还必须在实体Phone 中声明Id 类(Product)中的字段,并用@Id 对其进行注释。但IdClass 将用于复合主键。 也许this post 会有所帮助 【参考方案1】:

删除 Product 上的 @IdClass 注释,因为您没有自定义 id 提供者。

同时从 Phone 上的产品中删除 @Id 并添加一个 phoneID,如下所示:

@Id
private long phoneID;


@OneToOne
@JoinColumn(name = "productID", referencedColumnName = "productID")
private Product product;

【讨论】:

如果我删除 id 它会给出错误,因为表中没有 id “没有为实体指定标识符:com.test.project.data.entity.prod.Phone” 在Phone上添加一个单独的id字段,比如phoneID,用@Id注解。

以上是关于此类未定义 IdClass 外键的主要内容,如果未能解决你的问题,请参考以下文章