我有一个UserEntity和一个RoleEntity。UserEntity包含一个字段“roles”,该字段的类型为HashSet,并使用@ManyToMany注解进行注解。当调用我的自定义查询“findByEmail”时,它成功地获取了UserEntity,但roles集保持为空。
下面是部分代码:
UserEntity.java
package xyz.michaeltprojects.collchecklist.security.persistence;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
@Entity
@Table(name = "users")
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
public class UserEntity {
@Id
@GeneratedValue
private UUID id;
@NotBlank
@Size(min = 3, max = 30)
private String username;
@NotBlank
@Size(min = 6, max = 50)
@Email
private String email;
@NotBlank
@Size(max = 120)
private String password;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "user_roles", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<RoleEntity> roles = new HashSet<>();
}
字符串
RoleEntity.java
package xyz.michaeltprojects.collchecklist.security.persistence;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
import java.util.UUID;
@Entity
@Table(name = "roles")
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
public class RoleEntity {
@Id
@GeneratedValue
private UUID id;
@Enumerated(EnumType.STRING)
@Column(length = 20)
private ERole name;
}
型
UserRepository.java
package xyz.michaeltprojects.collchecklist.security.persistence;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
import java.util.UUID;
@Repository
public interface UserRepository extends JpaRepository<UserEntity, UUID> {
Optional<UserEntity> findByEmail(String email);
Boolean existsByUsername(String username);
Boolean existsByEmail(String email);
}
型
调用findByEmail方法时的输出
x1c 0d1x的数据
数据库表user_roles和roles
的
的
5条答案
按热度按时间tkqqtvp11#
我已经解决了这个问题.
70gysomp2#
你的
ManyToMany
不正确,你需要用referencedColumnName
引用每个表的id看看这个:
字符串
0g0grzrc3#
你能尝试一下吗?在UserEntity类下面添加一个覆盖函数setRoles(..)
字符串
lokaqttq4#
您必须从用户实体中删除
new HashSet<>();
。2w2cym1i5#
尝试使用
List roles = new ArrayList<>()
在我的代码中,我使用了Set with ManyToMany关系,在我将Set改为List之后,我没有得到任何关联的值。我不明白为什么Set with hashSet不起作用。