
在设计医生-患者关系管理系统时,一个核心挑战是如何有效地建模医生(doctor)、患者(patient)和药物(medicine)在此基础上,实现用户认证和权限管理的复杂关系。两个常见的初步思路是:
方案A:独立实体与多对多关联 将医生和病人分别设计成独立的实体,并通过 @ManyToMany 它是相关的。这种方法在数据模型中是直观的,但它可能需要维护不同用户类型的独立认证流程或端点,以实现医生和患者的登录和权限控制。
方案B:单用户表和角色管理 一般介绍 User 表,包含角色(如 RoleType 枚举),医生和病人都是 User 一种类型。这种方法简化了认证逻辑,但可能会导致 User 表中有大量的空字段(如医生没有药物列表,病人没有医生的独特属性),业务逻辑需要根据用户的角色来判断,导致代码冗余和复杂性的增加。
上述两种方案各有优缺点,但都有一定的局限性。方案A在安全管理上不够统一,而方案B在数据模型和业务逻辑上引入了不必要的耦合和冗余。因此,我们需要一个更好的混合方案。
2. 推荐的物理设计方案为了兼顾通用性、可扩展性和业务隔离性,建议采用混合实体设计模式:定义通用性 User 实体处理所有用户的基本信息和认证凭证,然后通过一对一的关系为医生和患者创建自己的专属实体 User 实体关联。
2.1 物理模型的定义User 实体: 作为所有用户的基础,包括ID等一般属性、姓名、姓氏和用户类型(用于权限判断)。
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
@Entity
@Table(name = "app_users") // 避免与数据库保留字冲突
@Getter
@Setter
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String surname;
private String username; // 用于登录的用户名
private String password; // 存储加密密码
@Enumerated(EnumType.STRING)
@Column(nullable = false)
private UserType userType; // 用户类型:DOCTOR, PATIENT, ADMIN等
}
// 用户类型枚举
public enum UserType {
DOCTOR,
PATIENT,
ADMIN
}
Doctor 实体: 它包含了医生的独特属性,并通过 @OneToOne 关联到 User 实体。@MapsId 注解确保 Doctor 主键与关联 User 主键相同,实现共享主键的一对一映射。
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
import java.util.HashSet;
import java.util.Set;
@Entity
@Getter
@Setter
public class Doctor {
@Id
private Long id; // 与User实体共享主要关键点
@OneToOne
@MapsId // 表示该实体的主键是其关联实体的主键
@JoinColumn(name = "id", nullable = false) // 外键列名
private User user;
// 医生和病人之间的多对多关系
@ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE}) // 级联操作
@JoinTable(
name = "doctor_patients", // 关系表名
joinColumns = @JoinColumn(name = "doctor_id"), // 关系表中本实体的外键
inverseJoinColumns = @JoinColumn(name = "patient_id") // 关系表中对方实体的外键
)
private Set<Patient> patients = new HashSet<>();
// 辅助方法,用于添加病人
public void addPatient(Patient patient) {
this.patients.add(patient);
patient.getDoctors().add(this); // 维持双向关系
}
// 辅助方法,用于移除病人
public void removePatient(Patient patient) {
this.patients.remove(patient);
patient.getDoctors().remove(this); // 维持双向关系
}
}
Patient 实体: 它还包括患者的独特属性,也包括患者的独特属性 @OneToOne 关联到 User 实体。
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Entity
@Getter
@Setter
public class Patient {
@Id
private Long id; // 与User实体共享主要关键点
@OneToOne
@MapsId
@JoinColumn(name = "id", nullable = false)
private User user;
// 患者与药物之间的多对多关系
@ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
@JoinTable(
name = "patient_medicines",
joinColumns = @JoinColumn(name = "patient_id"),
inverseJoinColumns = @JoinColumn(name = "medicine_id")
)
private Set<Medicine> medicines = new HashSet<>();
// 患者与医生之间的多对多关系(通过Doctor实体维护)
@ManyToMany(mappedBy = "patients", fetch = FetchType.LAZY) // mappedBy指向Doctor实体中维护关系的字段
private Set<Doctor> doctors = new HashSet<>();
// 辅助方法,用于添加药物
public void addMedicine(Medicine medicine) {
this.medicines.add(medicine);
medicine.getPatients().add(this); // 维持双向关系
}
// 辅助方法,用于去除药物
public void removeMedicine(Medicine medicine) {
this.medicines.remove(medicine);
medicine.getPatients().remove(this); // 维持双向关系
}
}
Medicine 实体: 药物信息。
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
import java.util.HashSet;
import java.util.Set;
@Entity
@Getter
@Setter
public class Medicine {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String description;
// 药物与患者之间的多对多关系(通过Patient实体维护)
@ManyToMany(mappedBy = "medicines", fetch = FetchType.LAZY)
private Set<Patient> patients = new HashSet<>();
}
该设计的优点是:
- 职责分离: User 负责认证和基本身份,Doctor 和 Patient 负责各自独特的业务属性和关系。
- 避免空字段: Doctor 和 Patient 表只包含自己独特的数据,避免单一数据 User 表中有大量的空字段。
- 灵活扩展: 如果未来有新的用户类型(如管理员、护士),只需要创建一个新的实体并与之联系起来。 User 即可。
- 统一认证: 所有用户都通过 User 实体认证简化了安全配置。
Spring Security 是 Spring 生态系统中强大的安全框架非常适合处理用户认证和授权。
3.1 用户认证流程-
UserDetailsService 实现: Spring Security 通过 UserDetailsService 加载用户信息的接口。根据用户名,我们需要实现这个接口 User 在实体中获取用户信息并将其转换为 Spring Security 的 UserDetails 对象。
import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.stereotype.Service; import java.util.Collections; @Service public class CustomUserDetailsService implements UserDetailsService { private final UserRepository userRepository; // 假设你有一个UserRepository public CustomUserDetailsService(UserRepository userRepository) { this.userRepository = userRepository; } @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user = userRepository.findByUsername(username) .orElseThrow(() -> new UsernameNotFoundException("User not found with username: " + username)); // 将Usertype转换为Spring SecurityGrantedAuthority return new org.springframework.security.core.userdetails.User( user.getUsername(), user.getPassword(), // 密码必须加密 Collections.singletonList(new SimpleGrantedAuthority("ROLE_" + user.getUserType().name())) ); } }在 User 实体中添加 username 和 password 并确保密码在存储前加密(例如使用) BCryptPasswordEncoder)。
-
Spring Security 配置: 配置 SecurityFilterChain(Spring Boot 2.7+ 推荐)或 WebSecurityConfigurerAdapter(旧版)定义认证方法、授权规则和密码编码器。
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.SecurityFilterChain; @Configuration @EnableWebSecurity public class SecurityConfig { @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .csrf(csrf -> csrf.disable()) // 禁用CSRF,方便测试,请注意生产环境 .authorizeHttpRequests(authorize -> authorize .requestMatchers("/api/public/**").permitAll() // 允许公共访问的API .requestMatchers("/api/doctors/**").hasRole("DOCTOR") // 只有DOCTOR角色才能访问 .requestMatchers("/api/patients/**").hasRole("PATIENT") // 只有PATIENT角色才能访问 .anyRequest().authenticated() // 所有其他要求都需要认证 ) .formLogin(form -> form .permitAll() // 允许所有人访问登录页允许所有人访问登录页 ) .logout(logout -> logout .permitAll() ); return http.build(); } }
通过控制器或服务层 @PreAuthorize 在代码中注释或获取当前认证用户的信息,然后根据 UserType 或其关联的 Doctor/Patient 实体执行特定的业务逻辑。
-
基于角色授权:
import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/api/doctors") public class DoctorController { @PreAuthorize("hasRole('DOCTOR')") // 只有DOCTOR角色才能访问 @GetMapping("/{doctorId}/patients") public List<Patient> getDoctorPatients(@PathVariable Long doctorId) { // 获取当前登录的医生,并返回相关患者名单 // 注:这里需要确保目前登录的医生ID与要求的doctorid相匹配,防止越权 return doctorService.findPatientsByDoctorId(doctorId); } } @RestController @RequestMapping("/api/patients") public class PatientController { @PreAuthorize("hasRole('PATIENT')") // 只有PATIENT角色才能访问 @PostMapping("/{patientId}/medicines") public void addMedicineToPatient(@PathVariable Long patientId, @RequestBody Medicine medicine) { // 只有目前登录的患者才能添加药物 patientService.addMedicine(patientId, medicine); } } -
获取当前用户信息: 可以通过 SecurityContextHolder 或 @AuthenticationPrincipal 获取当前登录用户 UserDetails 对象,然后得到它 User 实体,再根据 UserType 进一步加载 Doctor 或 Patient 实体。
import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; // 在服务层或控制器中 public User getCurrentAuthenticatedUser() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication != null && authentication.getPrincipal() instanceof UserDetails) { UserDetails userDetails = (UserDetails) authentication.getPrincipal(); // 根据userdetailss.getUsername()从UserRepository中获取完整的User实体 return userRepository.findByUsername(userDetails.getUsername()).orElse(null); } return null; } // 然后根据Usertype判断并加载特定的Doctor或Patient实体 public Doctor getCurrentDoctor() { User currentUser = getCurrentAuthenticatedUser(); if (currentUser != null && currentUser.getUserType() == UserType.DOCTOR) { return doctorRepository.findById(currentUser.getId()).orElse(null); } return null; }
在某些情况下,医生也可能是病人(例如,医生需要看医生才能生病)。这种混合物设计可以很好地支持这种情况。一个 User 实体可以同时关联到一个实体 Doctor 实体和一个 Patient 实体。当权限判断时,系统将根据其进行判断 UserType(或者更准确地说,根据它所拥有的角色列表)来决定它可以访问哪些资源和执行哪些操作。
例如,如果是一个 User 同时拥有 ROLE_DOCTOR 和 ROLE_PATIENT 如果有两个权限,他可以访问与医生或患者相关的API。业务逻辑层根据具体操作通过上下文 user.getId() 查询相应的 Doctor 或 Patient 实体执行操作。
4. 注意事项和最佳实践- 密码加密: 务必使用 PasswordEncoder 对用户密码进行加密存储,不要明文存储。
- 事务管理: 确保涉及多个实体操作的业务逻辑处于事务中,以确保数据的一致性。
- 懒加载(Lazy Loading): 默认使用多对多关系 FetchType.LAZY,避免加载不必要的数据,提高性能。只有在真正需要相关数据时才能加载。
- 级联操作(CascadeType): 谨慎使用 CascadeType.ALL。一般来说,对于一对一或一对多的关系,PERSIST 和 MERGE 足够了。在多对多关系中,通常只用于关系维护方 PERSIST 和 MERGE,避免删除不必要的级联。
- 服务层设计: 可以设计 UserService 处理一般用户操作,DoctorService 处理医生的特殊业务,PatientService 处理病人的独特业务。这些服务可以相互配合,但要保持各自的职责明确。
- API设计: 考虑为不同的角色设计不同的API路径前缀(如 /api/doctors 和 /api/patients),使权限控制更加直观。
- 异常处理: 实现统一的异常处理机制,为API调用提供友好的错误响应。
通过采用通用 User 实体和特定的角色实体(Doctor、Patient)结合设计模式,可以构建Spring,既能统一管理用户认证,又能灵活处理复杂的业务逻辑和实体关系 Boot应用程序。结合Spring Security,它可以实现强大而精细的权限控制,以确保医疗系统的数据安全和操作合规性。这种分层和模块化的设计理念不仅提高了代码的可维护性和可扩展性,而且为未来业务需求的变化预留了空间。
以上是Spring Boot 详细介绍了医疗系统的实体关系和安全实现指南,更多请关注图灵教育的其他相关文章!