org.hibernate.PropertyAccessException:无法使用Composite Key设置字段值

时间:2017-10-10 17:25:15

标签: java mysql spring hibernate

将Spring Boot与Hibernate JPA一起使用

我无法访问带有复合键的@Entity的DAO,其中一列是外键。它给了我 当我尝试使用DAO执行findOne()时,org.hibernate.PropertyAccessException: Could not set field value [...] by reflection

所以我有两个MySQL关系,all_contactscontact_phones,按此顺序表示:

all_contacts contact_phones

contact_phones有一个由contactid + number组成的复合主键,其中contactId也是all_contacts中相同值的外键}。我使用正确的@OneToMany@ManyToOne注释建立了关系

all_contacts的实体:

    @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

    }

contact_phones的实体:

@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类的主键是复合的(因此@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

1 个答案:

答案 0 :(得分:2)

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