簡體   English   中英

無法通過反射設置字段值

[英]Could not set field value by reflection

我有一個多對多關系的問題。 這些表格是:成分和營養價值。 我創建了兩個實體之間的關系表,其中有成分和營養價值的外部鍵(形成復合鍵)和一些屬性。

JoinedNutrionalValueIngredient

import lombok.Data;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.io.Serializable;

@Entity @Data
public class JoinedNutrionalValueIngredient implements Serializable {

    @EmbeddedId
    private NutrionalValueIngredientId id;

    @ManyToOne(fetch= FetchType.LAZY)
    @MapsId("ingredient_id")
    private Ingredient ingredient;

    @ManyToOne(fetch=FetchType.LAZY)
    @MapsId("nutrional_value_id")
    private NutrionalValue nutrionalValue;

    @NotNull
    String matrixUnit;

    @NotNull
    int value;

    @NotNull
    String valueType;
}

NutrionalValueIngredientId

import javax.persistence.*;
import java.io.Serializable;
import java.util.Objects;

@Embeddable
@Getter
@Setter
public class NutrionalValueIngredientId implements Serializable{

    @Column(name = "ingredient_id")
    private Long ingredient_id;

    @Column(name = "nutrional_value_id")
    private Long nutrional_value_id;

    public NutrionalValueIngredientId() {
        
    }   
   
    public NutrionalValueIngredientId(Long ingredient, Long nutrionalValue){
        this.ingredient_id=ingredient;
        this.nutrional_value_id=nutrionalValue;
    }
    
    public boolean equals(Object o) {
        if (this == o) return true;
    
        if (o == null || getClass() != o.getClass())
            return false;
    
        NutrionalValueIngredientId that = (NutrionalValueIngredientId) o;
        return Objects.equals(ingredient_id, that.ingredient_id) &&
                    Objects.equals(nutrional_value_id, that.nutrional_value_id);
    }
    
    @Override
    public int hashCode() {
        return Objects.hash(ingredient_id, nutrional_value_id);
    }
}

當我嘗試在關系表中插入一個新字段時,出現此錯誤:

{
  "timestamp": 1542653896247,
  "status": 500,
  "error": "Internal Server Error",
  "message": "Could not set field value [1] value by reflection : [class com.whateat.reciper.model.NutrionalValueIngredientId.ingredient_id] setter of com.whateat.reciper.model.NutrionalValueIngredientId.ingredient_id; nested exception is org.hibernate.PropertyAccessException: Could not set field value [1] value by reflection : [class com.whateat.reciper.model.NutrionalValueIngredientId.ingredient_id] setter of com.whateat.reciper.model.NutrionalValueIngredientId.ingredient_id",
  "path": "/v1/joinedNutrionalValueIngredients"
}

編輯:我添加了構造函數和注釋@Getter@Setter ,但我有同樣的錯誤。

NutritionalValue類:

@Data
@Entity
public class NutrionalValue implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotNull
    private String name;

    @NotNull
    private String unit;

    @NotNull
    private String source;

    @ManyToOne
    @NotNull
    @JoinColumn(name = "category_id")
    private NutrionalValueCategory category;

    @OneToMany(mappedBy = "nutrionalValue")
    private Set<JoinedNutrionalValueIngredient> joined = new HashSet<JoinedNutrionalValueIngredient>();

}

編輯:在 Debopam 的回答之后,這個錯誤就出來了。

{
  "timestamp": 1542657216244,
  "status": 500,
  "error": "Internal Server Error",
  "message": "null id generated for:class com.whateat.reciper.model.JoinedNutrionalValueIngredient; nested exception is org.hibernate.id.IdentifierGenerationException: null id generated for:class com.whateat.reciper.model.JoinedNutrionalValueIngredient",
  "path": "/v1/joinedNutrionalValueIngredients"
}

更改變量名稱如下

長成分_id到長成分id nutrional_value_id到nutrionalvalueid

例子

  @Column(name = "ingredient_id")
  Long ingredient_id;

@Column(name = "ingredient_id")
Long ingredientid;

然后為所有字段生成 getter setter。 Hibernate 無法設置字段,因為沒有公共 getter/setter。

 @Entity @Data
 public class JoinedNutrionalValueIngredient implements Serializable {
    
        @EmbeddedId
        private NutrionalValueIngredientId id = new NutrionalValueIngredientId();
    
    // ... rest of class  
 }

JoinedNutrionalValueIngredient類中,復合 id NutrionalValueIngredientId應該被實例化。

為 id 實體“NutrionalValueIngredientId”設置值,然后嘗試將其作為“JoinedNutrionalValueIngredient”的嵌入 id 插入。 參考下面的例子:

package com.example;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Embeddable;

@Embeddable
public class EmployeeId implements Serializable
{
private static final long serialVersionUID = 1L;
@Column(name = "EMP_ID")
private int empId;
@Column(name = "DEPARTMENT")
private String department;

public EmployeeId()
{
    super();
}
public EmployeeId(int empId, String department)
{
    super();
    this.empId = empId;
    this.department = department;
}

public int getEmpId()
{
    return empId;
}
public void setEmpId(int empId)
{
    this.empId = empId;
}
public String getDepartment()
{
    return department;
}
public void setDepartment(String department)
{
    this.department = department;
}
@Override
public int hashCode()
{
    final int prime = 31;
    int result = 1;
    result = prime * result + ((department == null) ? 0 : department.hashCode());
    result = prime * result + empId;
    return result;
}
@Override
public boolean equals(Object obj)
{
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    EmployeeId other = (EmployeeId) obj;
    if (department == null)
    {
        if (other.department != null)
            return false;
    } else if (!department.equals(other.department))
        return false;
    if (empId != other.empId)
        return false;
    return true;
}
 }

請參閱上面的嵌入式 ID 類(EmployeeId)。 這是 Employee 類的主鍵。 因此,我們需要在 Id 類(EmployeeId)中設置值,然后將該 id 類作為主鍵注入到 Employee 中。 然后它會起作用。 如果沒有主鍵,該值為空。

package com.example;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class Employee implements Serializable
{
private static final long serialVersionUID = 1L;
@EmbeddedId
EmployeeId id;
@Column(name="EMP_NAME")
private String empName;

public Employee()
{
    super();
}
public Employee(EmployeeId id, String empName)
{
    super();
    this.id = id;
    this.empName = empName;
}
public EmployeeId getId()
{
    return id;
}
public void setId(EmployeeId id)
{
    this.id = id;
}
public String getEmpName()
{
    return empName;
}
public void setEmpName(String empName)
{
    this.empName = empName;
}
} 

為 Id 類和其他字段設置值,如下所示。

 //Create a new Employee object   
 Employee employee = new Employee();

 EmployeeId employeeId = new EmployeeId(1,"DailyNews");
 employee.setEmpName("CompositeKey");
 employee.setId(employeeId);

 session.save(employee);

檢查您是否正在為嵌入式 ID 設置實例。 我不是並收到此錯誤。

我改變這個

@EmbeddedId
ProductUserId id;    

ProductUser(Integer productId, Integer UserId, Double rating){
    this.rating = rating
}

@EmbeddedId
ProductUserId id;    

ProductUser(Integer productId, Integer userId, Double rating){
    this.id = new ProductUserId(productId, userId);
    this.rating = rating
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM