在Hibernate JPA中使用Spring Boot
我在访问@Entity的DAO时遇到问题,该实体有一个组合键,其中一列是外键。它给了我
org.hibernate.PropertyAccessException: Could not set field value [...] by reflection当我尝试使用DAO执行findOne()时。
所以我有两个MySQL关系,all_contactscontact_phones,按顺序表示如下:
java - org.hibernate.PropertyAccessException:无法使用复合键设置字段值-LMLPHPjava - org.hibernate.PropertyAccessException:无法使用复合键设置字段值-LMLPHP
contact_phones有一个复合主键,由contactid+number组成,其中,contactId也是all_contacts中相同值的外键。我已经用适当的@OneToMany@ManyToOne注释建立了关系
所有联系人的实体:

    @Entity
    @Table(name = "all_contacts")
    public class Contact {

      @Column(name="userid", columnDefinition ="bigint(13)")
      private BigInteger userId;

      @Id
      @GeneratedValue(strategy = GenerationType.AUTO)
      @Column(name="contactid", columnDefinition ="bigint(13)")
      private BigInteger contactId;


     @OneToMany(mappedBy = "contact", cascade = CascadeType.ALL)
     @ElementCollection(targetClass=ContactPhones.class)
     private Set<ContactPhones> phones = new HashSet<ContactPhones>(0);

    // the rest of the fields, including getters and setters

    }

联系电话实体:
@Entity
@Table( name ="contact_phones")
@IdClass(ContactPhonesKey.class)
public class ContactPhones {


  @ManyToOne(fetch = FetchType.LAZY)
  @JoinColumn(name="contactid", nullable = false)
  @Id
  private Contact contact;

  @Column(name="phone_type", columnDefinition = "")
  private String phoneType;

  @Id
  @Column(columnDefinition ="bigint(13)")
  private BigInteger number;

  // getters and setters
}

而且,由于contact_phones类的主键是composite(因此是@IdClass(ContactPhonesKey.class)),我被迫创建一个key类来指导它:
ContactPhonesKey类:
public class ContactPhonesKey implements Serializable {

  private Contact contact;
  private String number;

  public ContactPhonesKey() {}

  public ContactPhonesKey(Contact contact, String number) {
    this.contact = contact;
    this.number = number;
  }

// getters and setters

}

但是,每当我试图通过DAO访问某个东西时(当我通过@Autowired创建了它的一个实例时),我就为contact_phones类创建了:
public interface ContactPhonesRepository extends CrudRepository<ContactPhones, BigInteger> {

  List<ContactPhones> findByNumberContaining(String number);


  @Query(value ="SELECT * FROM contact_phones cp WHERE cp.contactid= :contactId",
          nativeQuery=true)
  List<ContactPhones> findAllPhonesByContactId(@Param("contactId")BigInteger contactId);

}

由于反射,无法设置ContactPhonesKey类,我收到一个错误。这是我得到的全部错误:
Could not set field value [111456666] value by reflection : [class app.models.relationentities.ContactPhonesKey.number] setter of app.models.relationentities.ContactPhonesKey.number; nested exception is org.hibernate.PropertyAccessException: Could not set field value [111456666] value by reflection : [class app.models.relationentities.ContactPhonesKey.number] setter of app.models.relationentities.ContactPhonesKey.number

最佳答案

您的实体number和ID类ContactPhones之间的字段ContactPhonesKey上存在类型不匹配。在实体上,它声明为BigInteger,而在ID类上,它声明为String

07-24 15:34