English 中文(简体)
春天没有规划一套角色
原标题:Spring does not map set of roles

我与“春天框架”合作,我从许多对手表绘制一套角色图时遇到问题。 让我向各位介绍我的班子。

public class Role {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @NonNull
    private String authority;

    @ManyToMany(mappedBy = "roles", fetch = FetchType.EAGER/*, cascade=CascadeType.MERGE*/)
    private Set<AppUser> appUsers;

    public Role(@NonNull String authority) {
        this.authority = authority;
    }

    public Role() {

    }
}
public class AppUser implements Serializable {
    @Serial
    private static final long serialVersionUID = -8357820005040969853L;

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

    //    @NonNull
    @Column(unique = true)
    private /*final*/ String username;

    //    @NonNull
    private /*final*/ String password;

    @ManyToMany(fetch = FetchType.EAGER/*, cascade=CascadeType.MERGE*/)
//    @NonNull
    @JoinTable(name = "users_roles",
            joinColumns = @JoinColumn(name = "role_id"/*, referencedColumnName = "id"*/),
            inverseJoinColumns = @JoinColumn(name = "user_id"/*, referencedColumnName = "id"*/))
    private Set<Role> roles;
    }

这里是储蓄过程:

    @Bean
//    @Transactional
    public CommandLineRunner run(RoleRepository roleRepository, UserRepository userRepository, PasswordEncoder passwordEncoder) {
        return args -> {
            if (roleRepository.findByAuthority("ADMIN").isEmpty()) {
                Role admin = roleRepository.save(new Role("ADMIN"));
                Role user = roleRepository.save(new Role("USER"));

                userRepository.save(new AppUser("admin", passwordEncoder.encode("admin"), new HashSet<>() {
                    {
                        add(admin);
                        add(user);
                    }
                }));
            }
        };
    }

此时此刻,我想恢复用户的作用:

@Component
public class UserInterceptor implements HandlerInterceptor {
    private final UserRepository userRepository;
    private final RoleRepository roleRepository;

    public UserInterceptor(UserRepository userRepository, RoleRepository roleRepository) {
        this.userRepository = userRepository;
        this.roleRepository = roleRepository;
    }

    @Override
    public void postHandle(@NonNull HttpServletRequest request,
                           @NonNull HttpServletResponse response,
                           @NonNull Object handler,
                           ModelAndView modelAndView) {
        if (modelAndView != null) {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            Optional<AppUser> appUser = userRepository.findByUsername(authentication.getName());

            if (appUser.isPresent()) {
                Set<Role> set = roleRepository.findByAppUsers(new HashSet<>() {
                    {
                        add(appUser.get());
                    }
                });
                log.info("Roles for user {}: {}", appUser.get().getUsername(), appUser.get().getRoles());
                modelAndView.addObject("username", appUser.get().getUsername());
                modelAndView.addObject("roles", appUser.get().getRoles());
            } else
                modelAndView.addObject("username", "anonymous");
        }
    }
}

最令人感兴趣的部分是,当我把“行政”改为“行政”,就会看到我的用户在数据库中,我实际上在“联合国”一词中具有价值。 在检查存在后,我只建立了一套简单的检查套,在我通过用户物体检索的一套作用之后,它是否描绘了特定用户的作用。

And now comes the magic part: if I try to get roles from the user doing appUser.get().getRoles(), I get EMPTY SET OF ROLES IN THE appUser OBJECT. I mean, I could have tried to get all roles using an extra set created by userRepository.findByUsername, but I feel like it shouldn t work this way. Can anyone help me please, I would appreciate it and it would help me to get Spring framework. Thanks in advance. P.S. Here is the table from the database and yes, names of columns are messed up, I ve fixed it already.

“Database”/</a

问题回答

看来,像你一样,在Hibernate出现了一种令人厌恶的初始化问题,具体来说是在收集信息时发生的。

您可以把手法战略从 la改为热切希望使用@Fetch(FetchMode.JOIN)

@ManyToMany(fetch = FetchType.EAGER)
@Fetch(FetchMode.JOIN)
@JoinTable(name = "users_roles",
        joinColumns = @JoinColumn(name = "role_id"),
        inverseJoinColumns = @JoinColumn(name = "user_id"))
private Set<Role> roles;

指出,应当谨慎行事,因为这可能会产生许多影响,例如业绩恶化。





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签