[英]Unidirectional @OneToOne relationship with different Entities
I have a User
class:我有一个
User
class:
@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class User implements UserDetails {
@Id
@GeneratedValue
Long id;
@NotBlank
private String name;
@NotBlank
private String password;
private List<String> roles = new ArrayList<>();
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return this.roles.stream().map(SimpleGrantedAuthority::new).collect(toList());
}
@Override
public String getUsername() {
return null;
}
@Override
public boolean isAccountNonExpired() {
return false;
}
@Override
public boolean isAccountNonLocked() {
return false;
}
@Override
public boolean isCredentialsNonExpired() {
return false;
}
@Override
public boolean isEnabled() {
return false;
}
}
that models an user account that could be for a Student
or a Teacher
.对可能用于
Student
或Teacher
的用户帐户进行建模。 They can own only one account so to specify this relationship I thought to model it by a @OneToOne relationship but I'm having trouble understanding if it would be a good idea to make that unidirectional.他们只能拥有一个帐户,因此要通过@OneToOne 关系指定我认为与 model 的这种关系,但我无法理解将其设为单向是否是个好主意。
Also, the User
class could refer both to a Student
and a Teacher
by logic, what if I need to retrieve the details of the user starting from its User
account?另外,
User
class 在逻辑上可以同时引用Student
和Teacher
,如果我需要从User
帐户开始检索用户的详细信息怎么办? From my understanding, I should create a bi-directional relationship, but, which entity do I need to put inside the User
class?根据我的理解,我应该创建一个双向关系,但是,我需要在
User
class 中放入哪个实体?
You can use an enumeration:您可以使用枚举:
public enum UserType {
STUDENT("Student"),
TEACHER("Teacher");
private final String displayValue;
UserType(String displayValue) {
this.displayValue = displayValue;
}
public String getDisplayValue() {
return displayValue;
}
}
And in your user entity:在您的用户实体中:
@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class User implements UserDetails {
@Id
@GeneratedValue
Long id;
@NotBlank
private String name;
@NotBlank
private String password;
private List<String> roles = new ArrayList<>();
@Enumerated(EnumType.STRING)
private UserType userType;
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return this.roles.stream().map(SimpleGrantedAuthority::new).collect(toList());
}
@Override
public String getUsername() {
return null;
}
@Override
public boolean isAccountNonExpired() {
return false;
}
@Override
public boolean isAccountNonLocked() {
return false;
}
@Override
public boolean isCredentialsNonExpired() {
return false;
}
@Override
public boolean isEnabled() {
return false;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.