我有一个带有固定常量集的Ink类。它们永远不会改变,我也不想将此类存储为表格。

public final class Ink {
    public static final Ink Y = new Ink(91001, 'y', 90.70,  -5.23,  94.37), "Yellow");
    public static final Ink M = new Ink(92001, 'm', 48.19,  72.01,  -1.78), "Magenta");
    public static final Ink C = new Ink(93001, 'c', 56.46, -41.00, -43.50), "Cyan");
    public static final Ink K = new Ink(94001, 'k', 18.64,   1.80,   5.21), "Black");

    public int code;

    public static Ink forCode(int code) {
        //...
    }

    //...
}


其他类可以具有Ink inkCollection<Ink> inks字段,但是每个ink实例必须映射为具有其code值的简单整数列。 Code不是外键或其他东西–它是一个简单的整数值,我可以始终从中获取Ink实例。

@Entity
public class Order {
     //...
     @OneToMany
     public Set<Ink> inks;
     //...
}


我可以使用转换器通过其Ink还原code类并返回

@Converter(autoApply = true)
public class InkConverter implements AttributeConverter<Ink, Integer> {

     @Overrcodee
     public Integer convertToDatabaseColumn(Ink ink) {
         return ink.code;
     }

     @Overrcodee
     public Ink convertToEntityAttribute(Integer code) {
         return Ink.forCode(code);
     }
}


但问题是:

如何防止Hibernate将类映射为表,并且仍然从其code列加载类字段?

最佳答案

当您将墨水存储在Java代码中时。因此,您应该自己执行加载操作。首先,可以通过注释@Transient阻止Hibernate将类映射为表。然后您可以在加载订单后处理加载操作:

public interface Inked {
    getCode();
    setInk(Ink ink);
}

public abstract class AbstractEntity {

    @PostLoad
    public void loadInk() {
        if(this instanceof Inked){
            Inked inked = (Inked) this;
            inked.setInk(Ink.forCode(getCode()));
        }
    }
}

@Entity
public class Order extends AbstractEntity implement Inked {
    //...
    public Integer code;

    @Transient
    public Ink ink;
    //...

}

09-05 15:40