简体   繁体   English

休眠:ManyToMany单向仅返回一个记录

[英]Hibernate: ManyToMany unidirectional only returning one record

I have this problem and I'd appreciate any help... 我有这个问题,不胜感激。

I have a User entity. 我有一个用户实体。 A user has a Role (a many to one relationship). 用户具有角色(多对一关系)。 And a role has a list of permissions (the many to many relationshp I'm having trouble with). 角色具有权限列表(我遇到麻烦的许多关系)。

In my code, I am selecting a single user out of the database, by username. 在我的代码中,我要通过用户名从数据库中选择一个用户。

When I retrieve the user, the user's role is there inside of it. 当我检索用户时,该用户的角色就在其中。 But inside the role, there should be a list of permissions. 但是在角色内部,应该有一个权限列表。 There should be 4 permissions, but every time, I am only getting one element back in the set. 应该有4个权限,但是每次,我只返回一组元素。

I have queried the database correctly, and there are indeed 4 permissions attached to that role, so the problem isnt there. 我已经正确查询了数据库,并且确实有4个权限附加到该角色,所以问题不在那里。

UserEntity: 用户实体:

@Table(name = "users")
public class UserEntity {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  @NotEmpty
  private String username;

  @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
  @JoinColumn(name = "role_id")
  private RoleEntity role;
}

RoleEntity: RoleEntity:

@Table(name = "roles")
public class RoleEntity {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  @NotEmpty
  private String name;

  private String description;

  @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
  @JoinTable(name = "roles_permissions", joinColumns = @JoinColumn(name = "permission_id"),
      inverseJoinColumns = @JoinColumn(name = "role_id"))
  private Set<PermissionEntity> permissions = new HashSet<>();

}

And here is my repository. 这是我的资料库。 I'm calling this method from a service, and am just getting back what I described above. 我正在从服务中调用此方法,只是返回了我上面描述的内容。

@Repository
public interface UserRepository extends CrudRepository<UserEntity, String> {

  Optional<UserEntity> findByUsername(String username);
}

In my database, I have a table called 'roles_permissions' with the fields role_id and permission_id. 在我的数据库中,我有一个名为'roles_permissions'的表,其字段为role_id和Permission_id。 There are four records in here. 这里有四个记录。 role_id is '1' for all of them, and its linked to permissions 1,2,3,4. 所有角色的role_id均为“ 1”,其链接到权限1,2,3,4。

In the users table, there is a field for role_id. 在用户表中,有一个role_id字段。 And the user that I'm selecting has this field populated with 1. 我选择的用户的此字段填充为1。

Okay, nevermind. 好的没关系。 I've been working on this for a while, and I figured it out as soon as I posted this! 我已经为此工作了一段时间,当我发布此消息后,我就知道了!

In the @JoinTable annotation, I had "role_id" and "permission_id" the wrong way around! 在@JoinTable批注中,我错误地使用了“ role_id”和“ permission_id”!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM