【问题标题】:Spring boot - 'One To Many' attribute value type should not be ErrorSpring boot - “一对多”属性值类型不应为错误
【发布时间】:2021-05-23 15:54:33
【问题描述】:

我在 Spring Boot 中有我的 api。

我有 2 节课:

这是我的供应商类:

 public class Supplier{
     @OneToMany(cascade= {CascadeType.ALL})
     private List<Product> products;      <---  This one is working perfectly fine.

     @OneToMany(cascade= {CascadeType.ALL})
     private List<Ingredient> components;      <---- this is the line where I am getting an error

}

这是我收到的错误消息:

“一对多”属性值类型不应为“成分”

这是我的成分类

public class Ingredient {

     @Id
     @GeneratedValue
     private Long id;
     private String name;
     private String unit;
     private Double quantity = 0.0;
     private Double cost = 0.0;
     private Double price = 0.0;
}

我的问题: 上述错误的可能解决方法是:

private List<Ingredient> components;

即使它上面的那行是有效的?

【问题讨论】:

  • 假设Supplier 也是一个实体,那么请您告诉Ingredient 实体中的哪一列定义了与Supplier 实体的这种关联。您需要使用该列名称和附加注释@JoinColumn(name = "&lt;foreignKey&gt;")

标签: java spring spring-boot spring-mvc spring-data-jpa


【解决方案1】:

如果你有单向关联@OneToMany你需要替换

@OneToMany(cascade= {CascadeType.ALL})
private List<Ingredient> components; 

@OneToMany(cascade= {CascadeType.ALL})  
@JoinColumn(name="components")
private List<Ingredient> components; 

如果你想要一个双向关联 @OneToMany,你必须在你的 Ingredient 类中添加

...
@ManyToOne
@JoinColumn
private Supplier supplier;

供应商类没有任何变化 帮助您理解的链接

https://javabydeveloper.com/one-many-unidirectional-association/

https://javabydeveloper.com/one-to-many-bidirectional-association/

如果有帮助,请告诉我!

【讨论】:

  • @JoinColumn(name="components") 这告诉 Hibernate 在 'ingredients' 表中有一个 components 外键列定义了这个关联,而来自 Ingredient 实体,没有这样的列
  • @Haridarshan 感谢您的澄清,是不是没有指定具有关联@OneToMany(targetEntity = Ingredient.class)的类名称的问题@
【解决方案2】:

确保您正在注释您的类型类,在您的情况下是成分。它应该使用@Entity 进行注释。缺少注释您的类是产生此错误的原因之一。

【讨论】:

    猜你喜欢
    • 2020-07-03
    • 2015-11-14
    • 2013-05-06
    • 1970-01-01
    • 2021-07-13
    • 1970-01-01
    • 2021-12-26
    • 2016-02-27
    • 2021-01-23
    相关资源
    最近更新 更多