休眠:来自非实体 class 的实体 属性

Hibernate: Entity property from non-entity class

所以我有一个名为 Appointment 的休眠实体,在这个实体中我有一个 AppointNumber 属性,它本身包含一个数字 属性,它是一个字符串。 当我坚持我的约会时,我需要 AppointmentNumber。前几天我让它与@Embedded 和@Embeddable 一起工作,但这会创建一个我不能拥有的连接table。 我尝试了许多其他解决方案来尝试在不加入 tables 的情况下让它工作,但我无法弄清楚。 (我得到了很多ava.lang.IllegalStateException) 谁能帮忙? 谢谢!

@Entity(name = "appointments")
public class Appointment {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name = "id")
    private int id;

    @OneToOne(mappedBy = "number")
    @Fetch(value = FetchMode.SELECT)
    private AppointmentNumber appointmentNumber;

Appointment entity

AppointmentNumber, used in Appointment but should not be an entity

public class AppointmentNumber {

    @OneToOne
    @JoinColumn(name = "appointmentNumber", unique = true, nullable = false)
    private String number;

你可以这样做:

@Entity(name = "appointments")
public class Appointment {

  ///....
  @Convert(converter = AppointmentNumberConverter.class)
  private AppointmentNumber appointmentNumber;
  ///....
}


@Converter
public class AppointmentNumberConverter implements 
AttributeConverter<PersonName, String> {

  @Override
  public String convertToDatabaseColumn(AppointmentNumber appointmentNumber) {
    if (appointmentNumber == null) {
        return null;
    }

    return appointmentNumber.getNumber();
  }

  @Override
  public AppointmentNumber convertToEntityAttribute(String appointmentNumber) {
    if (appointmentNumber == null) {
        return null;
    }
    AppointmentNumber result = new AppointmentNumber();
    result.setNumber(appointmentNumber);
    return result;
  }
}

查看 JPA 转换器文档。