【问题标题】:This class does not define an IdClass foreign key此类未定义 IdClass 外键
【发布时间】: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

【问题讨论】:

标签: java spring jpa crud


【解决方案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注解。
猜你喜欢
  • 1970-01-01
  • 2020-06-10
  • 2020-04-08
  • 2015-03-08
  • 1970-01-01
  • 2021-04-03
  • 2012-05-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多