postgresql @ManyToMany values are always null

5f0d552i  于 2022-12-12  发布在  PostgreSQL
关注(0)|答案(1)|浏览(123)

I have this POJO 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 = "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.

I have tried changing data to @OneToOne, @ManyToOne, @OneToMany.But its always null.At some point, when i was doing @ManyToOne way, i have got this exception:
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.weather.weather.entity.Role.users: could not initialize proxy - no Session
And i found to ways to fix that. I`ve tried putting fetch property, @Proxy(lazy=false), and many many others. Nothing helped

lf5gs5x2

lf5gs5x21#

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

相关问题