简体   繁体   中英

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.

I have queried the database correctly, and there are indeed 4 permissions attached to that role, so the problem isnt there.

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:

@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. There are four records in here. role_id is '1' for all of them, and its linked to permissions 1,2,3,4.

In the users table, there is a field for role_id. And the user that I'm selecting has this field populated with 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!

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.

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