Hibernate:为类提供了错误类型的ID

voase2hg  于 2022-11-14  发布在  其他
关注(0)|答案(1)|浏览(111)

在尝试将StudentID保存到Student_ID表时,我遇到了下面的异常。我不知道如何保存具有复合主键的实体本身。
Org.hibernate.TypeMismatchException:为类StudentIdEntity提供了错误类型的ID。应为:StudentIdEntity,获取类java.lang.Long|ConsoleCatcherOutputStream:write
下面是我的代码:

@Entity
@Table(name = "STUDENT_ID")
@IdClass(StudentIdEntity.class)
public class StudentIdEntity implements Serializable {
    @Id
    @Column(name = "ID_1")
    private Long id1;
    @Id
    @Column(name = "ID_2", nullable = false)
    private Long id2;

    public StudentIdEntity() {
    }

    public Long getId1() {
        return id1;
    }

    public void setId1(Long id1) {
        this.id = id1;
    }

    public Long getLocationId2() {
        return id2;
    }

    public void setLocationId2(Long id2) {
        this.id2 = id2;
    }
}

StudentIdEntity studentIdEntity = new StudentIdEntity();
studentIdEntity.setId1(id1);
studentIdEntity.setId2(id2);
studentImplement.save(studentIdEntity);
f87krz0w

f87krz0w1#

您已经了解了如何组合主键。有两种方法可以使用@IdClass()@EmbeddedId()组合主键。您已经为复合主键创建了单独类。

  • 首先必须创建类StudentId.java,然后将其传递到IdClass注解中。

下面是使用IdClass组合主键的代码:

StudentId.Java

public class StudentId implements Serializable {
    private Long id1;
    private Long id2;

    // default constructor

    public StudentId(Long id1, Long id2) {
        this.id1 = id1;
        this.id2 = id2;
    }

    // equals() and hashCode()
}
@Entity
@Table(name = "STUDENT_ID")
@IdClass(StudentId.class)
public class StudentIdEntity {
    @Id
    @Column(name = "ID_1")
    private Long id1;

    @Id
    @Column(name = "ID_2", nullable = false)
    private Long id2;

    // default constructor, constructer, getter and setter
}

StudentIdEntity studentIdEntity = new StudentIdEntity();
studentIdEntity.setId1(id1);
studentIdEntity.setId2(id2);
studentImplement.save(studentIdEntity);

有关更多信息,请参阅此处如何在Hibernate中定义复合外键Map?

相关问题