绑定两个实体,无需中间实体的 Spring Data JPA。

huangapple go评论118阅读模式
英文:

Bind two Entity without intermediate Entity spring data jpa

问题

我有一个用户表(和实体)

  1. create table users(
  2. id number(9) not null,
  3. alias varchar2(200 char),
  4. name_en varchar2(200 char),
  5. state varchar2(1) not null
  6. );

以及用户组

  1. create table user_groups(
  2. group_id number(9) not null,
  3. alias varchar2(200) not null,
  4. name_en varchar2(200 char),
  5. state varchar2(1) not null,
  6. constraint user_groups1 primary key (group_id)
  7. );

组用户存储在绑定表中

  1. create table user_group_binds(
  2. group_id number(9) not null,
  3. user_id number(9) not null,
  4. constraint user_group_binds1 foreign key (group_id) references user_groups(group_id),
  5. constraint user_group_binds2 foreign key (user_id) references users(id)
  6. );

我想要在我的组实体中拥有用户实体的列表(不包括绑定实体)。有任何想法吗?
当然,我可以使用@Query注释,但我有其他与组映射的实体,它们将自动获取组实体。
我可以覆盖自动生成的方法吗?

英文:

I have a user table(and entity)

  1. create table users(
  2. id number(9) not null,
  3. alias varchar2(200 char),
  4. name_en varchar2(200 char),
  5. state varchar2(1) not null
  6. );

and user groups

  1. create table user_groups(
  2. group_id number(9) not null,
  3. alias varchar2(200) not null,
  4. name_en varchar2(200 char),
  5. state varchar2(1) not null,
  6. constraint user_groups1 primary key (group_id)
  7. );

group users are stored in bind table

  1. create table user_group_binds(
  2. group_id number(9) not null,
  3. user_id number(9) not null,
  4. constraint user_group_binds1 foreign key (group_id) references user_groups(group_id),
  5. constraint user_group_binds2 foreign key (user_id) references users(id)
  6. );

I want to have in my group entity list of userEntity(without bind entity). Any ideas?
Of course, I can use @Query annotation, but I have other entities who mapped with group and they will automatic get group entity.
Can I override automatical methods?

答案1

得分: 1

您可以使用 @JoinTable 并在 UserGroup 实体中定义与联接表的列映射。

  1. @OneToMany(cascade = CascadeType.ALL)
  2. @JoinTable(name = "user_group_binds",
  3. joinColumns = {@JoinColumn(name = "group_id", referencedColumnName = "group_id")},
  4. inverseJoinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")})
  5. List<UserEntity> users;
英文:

You can use @JoinTable and define column mapping with join table in UserGroup Enitity

  1. @OneToMany(cascade = CascadeType.ALL)
  2. @JoinTable(name = &quot;user_group_binds&quot;,
  3. joinColumns = {@JoinColumn(name = &quot;group_id&quot;, referencedColumnName = &quot;group_id&quot;)},
  4. inverseJoinColumns = {@JoinColumn(name = &quot;user_id&quot;, referencedColumnName = &quot;id&quot;)})
  5. List&lt;UserEntity&gt; users;

huangapple
  • 本文由 发表于 2020年7月30日 14:53:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/63167718.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定