[英]Spring Data JPA - @GeneratedValue annotation shows no affect
I have a problem regarding my implementation of a weak entity type.我在实施弱实体类型时遇到问题。 (Note, if that's important: I'm using H2 as my database)
(注意,如果这很重要:我使用 H2 作为我的数据库)
Here is my datamodel:这是我的数据模型:
I'm trying to implement Activity's concatenated primary key using two @ID annotated columns.我正在尝试使用两个带@ID 注释的列来实现 Activity 的串联主键。 Here is my activity class as well as its "owner"-class:
这是我的活动 class 及其“所有者”类:
@Entity
public class Activity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Id
@ManyToOne
@JoinColumn
private UserGroup group;
...
}
@Entity
public class UserGroup {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
...
}
My expected outcome would be, that inside my activity table id is generated by default as identity and group_id is set depending on the corresponding group-join.我的预期结果是,我的活动表中的 id 是默认生成的,因为 identity 和 group_id 是根据相应的 group-join 设置的。 Basically something like this:
基本上是这样的:
create table activity
(
id bigint generated by default as identity,
begin_date_time timestamp(6),
end_date_time timestamp(6),
name varchar(255) not null,
note varchar(255),
group_id bigint not null,
room_id bigint,
primary key (group_id, id)
);
Instead, spring disregards my @GeneratedValue annotation and sets it to group_id, ignoring my actual activity.id column:相反,spring 忽略了我的 @GeneratedValue 注释并将其设置为 group_id,忽略了我的实际 activity.id 列:
create table activity
(
id bigint not null,
begin_date_time timestamp(6),
end_date_time timestamp(6),
name varchar(255) not null,
note varchar(255),
group_id bigint generated by default as identity,
room_id bigint,
primary key (group_id, id)
);
This is a problem, as I plan on using Rest-Endpoints and Repositories to run CRUD operations using HTTP-requests.这是一个问题,因为我计划使用 Rest-Endpoints 和 Repositories 来使用 HTTP 请求运行 CRUD 操作。 Having an ID-counter that increments and gets new IDs for one table only seems unnecessary and dirty.
拥有一个 ID 计数器来增加和获取一个表的新 ID 似乎是不必要的和肮脏的。
Can somebody explain to me why this is happening?有人可以向我解释为什么会这样吗? Can I manually annotate group_id as a manually assigned field as a quick workaround?
我可以手动将 group_id 注释为手动分配的字段作为快速解决方法吗?
Cheers!干杯!
What you are looking for is a composite key, which you can create with either @IdClass
or with @Embeddable
and @EmbeddedId
.您正在寻找的是一个复合键,您可以使用
@IdClass
或@Embeddable
和@EmbeddedId
创建它。 The catch is, however, that neither of these approaches will work with a @GeneratedId.然而,要注意的是,这些方法都不适用于@GeneratedId。
If you think about it, there's no need to have a composite key where one of the parts is autogenerated.如果您考虑一下,就不需要在其中一个部分自动生成的情况下使用复合键。 Just have one Id on your entity that's auto generated, and if you want, create an index across
(group_id, id)
.只需在您的实体上有一个自动生成的 Id,如果需要,可以跨
(group_id, id)
创建一个索引。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.