我有一个包含元素集合的实体类 PositionOrdering:
@ElementCollection(targetClass = Position.class, fetch = FetchType.EAGER)
@CollectionTable(name = "POSITION_ORDERING_POSITION",
joinColumns = @JoinColumn(name = "position_ordering_id"))
@OrderColumn
List<Position> positions = new ArrayList<>();
当hibernate生成数据库结构时,它看起来是这样的:
CREATE TABLE wls.position_ordering_position
(
position_ordering_id bigint NOT NULL,
positions_id bigint NOT NULL,
positions_order integer NOT NULL,
...
}
没关系,完全符合我的预期。 但它还在 positions_id
列上生成一个唯一的约束。这很奇怪,因为位置 id 应该只在每个订单中是唯一的,所以以下任何唯一键都可以:
- position_ordering_id + positions_order
- position_ordering_id + positions_id
但不在 positions_id 的单列上。
因为约束是自动生成的,所以我不能简单地忽略或删除它。
我能否配置我的集合以创建正确的唯一约束或至少不创建任何唯一约束?
更新:
至于请求,这里是 Position 实体的骨架:
@Entity
@SequenceGenerator(name = EntityBase.SEQUENCE_NAME,
sequenceName = "POSITION_ID_SEQ")
@Table(name = "position")
public class Position extends EntityBase {
// Lots of fields, like row, column number, and type, etc.
}
其中 EntityBase 是一个具有一些实用函数和 Id 的简单类:
@MappedSuperclass
public abstract class EntityBase implements Serializable, Cloneable {
public static final String SEQUENCE_NAME = "SEQUENCE_GENERATOR";
@Id
@GeneratedValue(strategy = GenerationType.AUTO, generator = SEQUENCE_NAME)
protected Long id;
//..
}
最佳答案
@ElementCollection
用于映射基本类型或 @Embedded
类,而不是实体。来自 the documentation
An ElementCollection can be used to define a one-to-many relationship to an Embeddable object, or a Basic value (such as a collection of Strings).
由于 Position
是一个 @Entity
,您应该将其映射为 @OneToMany
或 @ManyToMany
。我不知道您生成该唯一 key 的确切原因,但我想如果您在 a was 中使用不是预期的注释,则可能会出现不可预测的结果。
关于sql - JPA @ElementCollection 生成奇怪的唯一键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28108407/