@ManyToMany值始终为 null

@ManyToMany values are always null

提问人: 提问时间:12/7/2022 更新时间:12/7/2022 访问量:312

问:

我有这个POJO类: 包 com.weather.weather.entity;

import jakarta.persistence.*;import lombok.Data;
import lombok.NoArgsConstructor;import org.hibernate.annotations.Proxy;import org.springframework.transaction.annotation.Transactional;
import java.util.List;import java.util.Set;
@Entity@Table(name = "users")@Data@NoArgsConstructor
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)

private Long id;

@Column(name = "username")
private String username;

@Column(name = "password")
private String password;



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

Also Role class:

package com.weather.weather.entity;

import jakarta.persistence.*;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.Proxy;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;

@Entity
@Table(name = "roles")
@Data
@NoArgsConstructor
public class Role {

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


    private String name;


//    @OneToMany(mappedBy = "role")
//    private List<User> users;

    @ManyToMany(mappedBy = "roles")
    private Set<User> users;


}
But always getRoles() are null.

我尝试将数据更改为 @OneToOne、@ManyToOne @OneToMany.但它总是空的。在某个时候,当我以@ManyToOne方式做事时,我遇到了这个例外:

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.weather.weather.entity.Role.users: could not initialize proxy - no Session

我找到了解决这个问题的方法。我试过放置 fetch 属性、@Proxy(lazy=false) 等等。没有任何帮助

java 数据库 postgresql null

评论


答:

0赞 Mavlyan Sadirov 12/7/2022 #1

您的注释@ManyToMany从 jakarta.persistence 导入的。 您应该从 javax.persistence.* 导入,并且可以删除代理注释和 Lazy fetchType

评论

0赞 12/7/2022
是的,它起作用了,但新问题是 Spring Boot 现在看不到 Spring Security 的配置,它给了我默认的配置