我有一个可嵌入的类定义为;
@Embeddable
public class Observation{
@Column(name = "created")
private LocalDateTime created;
@Column(name="code")
private string code
---
}
我的实体类是;
@Entity
@Table(name = "mete_observation", uniqueConstraints = @UniqueConstraint(columnNames = "code"),
public class MeterObservation{
@Embedded
@AttributeOverrides({ @AttributeOverride(name = "created", column = @Column(name = "ob_created")) })
private Observation raw = null;
}
我想创建索引观察/创建字段和观察/代码。
创建索引的最佳方法是什么?我应该在Embeddable类中定义它们吗?或者我可以从实体类中定义它吗?我该如何定义?任何一个例子。
答案 0 :(得分:0)
向嵌入式对象添加索引可能会有些棘手。为了使它起作用,必须使用确切的列名。
由于created
列名被AttributeOverrides
覆盖,因此索引的列不称为created
,而是ob_created
。
没有其他配置,索引看起来像这样:
@Entity
@Table(
name = "mete_observation",
uniqueConstraints = @UniqueConstraint(columnNames = "code"),
indexes = {
@Index(columnList = "ob_created", name = "idx_created"), // not 'created' but 'ob_created' as it is overwritten
@Index(columnList = "code", name = "idx_code"),
}
)
public class MeterObservation{
@Embedded
@AttributeOverrides({ @AttributeOverride(name = "created", column = @Column(name = "ob_created")) })
private Observation raw = null;
}
(已通过JPA 2.2.3和Hibernate 5.4.15测试。)
如果命名的隐式策略已设置为ImplicitNamingStrategyComponentPathImpl
,则会增加其他复杂性。那也会改变列名。
@Entity
@Table(
name = "mete_observation",
uniqueConstraints = @UniqueConstraint(columnNames = "code"),
indexes = {
@Index(columnList = "ob_created", name = "idx_created"), // the AttributeOverride 'ob_created' beats the naming strategy
@Index(columnList = "raw_code", name = "idx_code"), // adding 'raw_' for the naming strategy
}
)
public class MeterObservation{
@Embedded
@AttributeOverrides({ @AttributeOverride(name = "created", column = @Column(name = "ob_created")) })
private Observation raw = null;
}