我有一个管理用户、用户配置文件和角色的 springboot 应用程序
一个用户只能有一个配置文件(我想要一个单向关系,我只需要从用户导航 - >用户配置文件)
一个用户可以有很多“角色”(权限),我想要一个多对多的关系
这是实体的代码:
用户
@AllArgsConstructor
@RequiredArgsConstructor
@EqualsAndHashCode(callSuper = true)
@Entity
@Table(name = "users")
public class User extends AbstractAuditingEntity<Long> {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "user_id")
private Long id;
@NotBlank
@Size(max = 15)
private String username;
@NaturalId
@NotBlank
@Size(max = 40)
@Email
private String email;
@NotBlank
@Size(max = 100)
private String password;
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "user_roles", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> roles = new HashSet<>();
@OneToOne(mappedBy = "user", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JsonManagedReference
private UserProfile userProfile;
}
UserProfile (@OneToOne with User)
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name="user_profile")
public class UserProfile {
@Id
@Column(name="user_id")
private Long id;
@Column(name="first_name")
private String firstName;
@Column(name="last_name")
private String lastName;
@Column(name = "phone_number")
@Size(max = 15)
private String phoneNumber;
@OneToOne
@MapsId
@JoinColumn(name = "user_id")
@JsonBackReference
private User user;
}
角色(@ManyToMany 与用户)
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name="roles")
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="role_id")
private Long id;
@Enumerated(EnumType.STRING)
@NaturalId
@Column(length = 60)
private RoleName name;
}
我正在尝试仅通过 DTO 类获取具有 UserProfile 的用户:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserWithProfileDto {
private String username;
private String email;
private String password;
private UserProfile userProfile;
}
查询如下:
@Query("""
select new com.springboot.jwtstarter.domain.dto.UserRolesDto
(u.username, u.email, u.password, u.userProfile)
from User u
where u.id = (:id)
""")
Optional<UserRolesDto> findUserRoleDtoById(Long id);
我想在一个查询中这样做但是控制台显示了2个查询:
select u1_0.username,u1_0.email,u1_0.password,u2_0.user_id,u2_0.first_name,u2_0.last_name,u2_0.phone_number from users u1_0 join user_profile u2_0 on u1_0.user_id=u2_0.user_id where u1_0.user_id=?
select u1_0.user_id,u1_0.created_by,u1_0.created_date,u1_0.email,u1_0.last_modified_by,u1_0.last_modified_date,u1_0.password,u1_0.username from users u1_0 where u1_0.user_id=?
我想澄清以下几点: