I have a problem regarding my implementation of a weak entity type. (Note, if that's important: I'm using H2 as my database)
I'm trying to implement Activity's concatenated primary key using two @ID annotated columns. Here is my activity class as well as its "owner"-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. 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:
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. Having an ID-counter that increments and gets new IDs for one table only seems unnecessary and dirty.
Can somebody explain to me why this is happening? Can I manually annotate group_id as a manually assigned field as a quick workaround?
Cheers!
What you are looking for is a composite key, which you can create with either @IdClass
or with @Embeddable
and @EmbeddedId
. The catch is, however, that neither of these approaches will work with a @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)
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.