小编典典

无法在具有@IdClass的实体中转换请求元素

hibernate

我有以下设置:

@Entity
@IdClass(MemberAttributePk.class)
public class MemberAttribute {
    @Id
    @ManyToOne @JoinColumn(name="member_id")
    protected Member member;

    @Id
    protected String name;

    private String value;

    public MemberAttribute() {}

    // get & set
}

和id类:

public class MemberAttributePk implements Serializable {
    protected Member member;
    protected String name;

    public MemberAttributePk() {}

    // get & set
}

我已经为定义了一个简单的Spring Data存储库MemberAttribute

@Repository
public interface MemberAttributeRepo extends JpaRepository<MemberAttribute, MemberAttributePk> {
}

现在,我要做的就是将成员属性持久保存到数据库中:

public void saveAttribute(Member member, String name, String value) {
    MemberAttribute attr = new MemberAttribute(member, name, value);
    attributeRepo.save(attr);
}

但是,我最终遇到此服务器异常:

2016-08-28 00:24:20.673  WARN 5656 --- [nio-8080-exec-8] .w.s.m.s.DefaultHandlerExceptionResolver : 
Failed to convert request element: org.springframework.beans.ConversionNotSupportedException: 
Failed to convert property value of type [java.lang.Long] to required type [com.example.Member] for property 'member'; nested exception is java.lang.IllegalStateException: 
Cannot convert value of type [java.lang.Long] to required type [com.example.Member] for property 'member': 
no matching editors or conversion strategy found

知道我在做什么错吗?谢谢!


阅读 402

收藏
2020-06-20

共1个答案

小编典典

只是您的代码不符合JPA。问题的原因是您将其Member用作PK的一部分。 PK只能由以下Java类型的字段组成

  1. 基元 :布尔值,字节,字符,整数,长,短
  2. java.lang :布尔值,字节,字符,整数,长,短,字符串,枚举,StringBuffer
  3. java.math :BigInteger java.sql:Date,Time,Timestamp
  4. java.util :日期,货币,语言环境,时区,UUID
  5. **java.net** :URI,URL
  6. javax.jdo.spi :PersistenceCapable

这应该工作:

@Embeddable
public class MemberAttributePk implements Serializable {
    @Column(name = "member_id")
    protected Long memberId;
    @Column(name = "name")
    protected String name;

    public MemberAttributePk() {}

    // get & set
}

@Entity
public class MemberAttribute {

    @EmbeddedId
    protected MemberAttributePk memberAttributePk;

    @ManyToOne 
    @JoinColumn(name="member_id")
    protected Member member;

    private String value;

    public MemberAttribute() {}

    // get & set
}

还是一样 @ClassId

public class MemberAttributePk implements Serializable {
    protected Long memberId;
    protected String name;

    public MemberAttributePk() {}

    // get & set
}

@Entity
@IdClass(MemberAttributePk.class)
public class MemberAttribute {
    @Id
    @Column(name = "member_id")
    protected Long memberId;

    @Id
    @Column(name = "name")
    protected String name;

    @ManyToOne 
    @JoinColumn(name="member_id")
    protected Member member;

    private String value;

    public MemberAttribute() {}

    // get & set
}
2020-06-20