Hibernate对象ID

时间:2017-09-22 09:07:04

标签: java hibernate

我试图将对象用作@Id,但Hibernate似乎并没有将对象转换为使用AttributeConverter声明的相应基本类型。

@Entity
@Table(name = "ris_exam")
public class Exam {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(name = "id")
  private long examId;
}


public class ExamId  {
  private Long id;
  public ExamId(final Long id) {
    super();
    this.id = id;
  }

  public Long getId() {
    return this.id;
  }
}




@Converter(autoApply = true)
public class ExamIdCodeAttributeConverter implements AttributeConverter<ExamId, Long> {

  @Override
  public Long convertToDatabaseColumn(ExamId arg0) {
    return arg0.getId();
  }

  @Override
  public ExamId convertToEntityAttribute(Long arg0) {
    return new ExamId(arg0);
  }
}

Hibernate在创建表时执行此查询

create table ris_exam (id varbinary(255) identity not null, ...)

1 个答案:

答案 0 :(得分:0)

如果您想要使用基本列的包装,那么您必须考虑到您很可能无法在您的ID上使用@GeneratedValue注释(同样适用于使用{{在我看来,这比转换器更适合)。

如果您还需要,那么在我看来您可以尝试@EmbeddedId功能,但请记住@IdClass类只会在指定查询/检索特定实体时使用:

ExamId
DAO中的

@Entity
@Table(name = "ris_exam")
@IdClass(ExamId.class)
public class Exam {
   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   @Column(name = "id")
   private long examId;
}

检索时,实体将包含普通长类型。

您可以考虑选择..