You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring JPA关联关系更新失效:无法添加学生至班级

问题:添加学生到班级功能无效果

我正在开发一款「校园电子日记」应用,目前尝试实现将学生添加到班级的功能,但遇到了问题:尝试将实体添加到实体列表时,没有任何效果。


接收请求的控制器代码

@RestController
@RequestMapping("/api/admin/class")
public class AdminClassController {
    @Autowired
    private AdminService adminService;

    @Autowired
    private ClassService classService;

    @PostMapping("/user")
    public ResponseEntity<Object> addUserToClass(@RequestBody AdminAddUserToClassModel userAndClassData) {
        try {
            return ResponseEntity.ok(adminService.addUserToClass(userAndClassData));
        } catch (UserNotFoundException | ClassNotFoundException e) {
            return new ResponseEntity<>(e.getMessage(), HttpStatus.NOT_FOUND);
        } catch (UserAlreadyExistsException e) {
            return new ResponseEntity<>(e.getMessage(), HttpStatus.FORBIDDEN);
        }
    }
}

AdminService实现代码

@Service
public class AdminService {
    @Autowired
    private UserService userService;

    @Autowired
    private UserRepository userRepo;

    @Autowired
    private SchoolRepository schoolRepo;

    @Autowired
    private SchoolService schoolService;

    @Autowired
    private ClassService classService;

    @Autowired
    private ClassRepository classRepo;

    public ClassEntity addUserToClass(AdminAddUserToClassModel userAndClassModel)
            throws UserNotFoundException, ClassNotFoundException, UserAlreadyExistsException {
        UserEntity user = userService.getUserEntity(userAndClassModel.getUserId());
        ClassEntity schoolClass = classService.getClassEntity(userAndClassModel.getClassId());
        if(schoolClass.getStudents().contains(user)) {
            throw new UserAlreadyExistsException("user already in this class");
        }
        schoolClass.getStudents().add(user);
        classRepo.save(schoolClass);
        userRepo.save(user);
        return schoolClass;
    }
}

在addUserToClass方法中,尝试将UserEntity添加到ClassEntity并保存后,没有任何变化!


UserService的getUserEntity方法

public UserEntity getUserEntity(long userId) throws UserNotFoundException {
        return userRepo.findById(userId)
                .orElseThrow(() -> new UserNotFoundException("user with id " + userId + " not found"));
    }

ClassService的getClassEntity方法

public ClassEntity getClassEntity(long classId) throws ClassNotFoundException {
        return classRepo.findById(classId)
                .orElseThrow(() -> new ClassNotFoundException("class with such id doesn't exists"));
    }

实体类定义

UserEntity

@Entity
@Table(name = "users", schema = "working_schema")
public class UserEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    @Getter @Setter
    private long id;

    @Getter @Setter
    private String login;

    @Getter @Setter
    private String password;

    @Getter @Setter
    private String phoneNumber;

    @Getter @Setter
    private String email;

    @Getter @Setter
    private String name;

    @Getter @Setter
    private String surname;

    @Getter @Setter
    private String patronymic;

    @ManyToOne
    @JoinColumn(name = "roleid", nullable = false)
    @Getter @Setter
    private RoleEntity role;

    @ManyToOne
    @JoinColumn(name = "classid")
    @Getter @Setter
    private ClassEntity userClass;

    @ManyToOne
    @JoinColumn(name = "schoolid")
    @Getter @Setter
    private SchoolEntity school;


    public UserEntity() {
    }
}

ClassEntity

@Entity
@Table(name = "classes", schema = "working_schema")
public class ClassEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    @Getter @Setter
    private long id;

    @Getter @Setter
    private int number;

    @Getter @Setter
    private char letter;

    @OneToMany(mappedBy = "userClass", cascade = CascadeType.ALL)
    @Getter @Setter
    @JsonIgnore
    private List<UserEntity> students;

    @ManyToOne
    @JoinColumn(name = "schoolid")
    @Getter @Setter
    private SchoolEntity school;

    @OneToOne
    @JoinColumn(name = "timetableid")
    @JsonIgnore @Getter
    @Setter
    private TimetableEntity timetable;

    public ClassEntity() {
    }
}

SchoolEntity

@Entity
@Table(name = "schools", schema = "working_schema")
public class SchoolEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    @Getter @Setter
    private long id;

    @Getter @Setter
    private long number;

    @OneToMany(mappedBy = "school", cascade = CascadeType.ALL)
    @Getter @Setter
    @JsonIgnore
    private List<UserEntity> students;

    @OneToMany(mappedBy = "school", cascade = CascadeType.ALL)
    @Getter @Setter
    @JsonIgnore
    private List<ClassEntity> classes;
}

更新:执行时的SQL查询语句

Hibernate: 
    select
        classentit0_.id as id1_0_0_,
        classentit0_.letter as letter2_0_0_,
        classentit0_.number as number3_0_0_,
        classentit0_.schoolid as schoolid4_0_0_,
        classentit0_.timetableid as timetabl5_0_0_,
        schoolenti1_.id as id1_2_1_,
        schoolenti1_.number as number2_2_1_,
        timetablee2_.id as id1_4_2_ 
    from
        working_schema.classes classentit0_ 
    left outer join
        working_schema.schools schoolenti1_ 
            on classentit0_.schoolid=schoolenti1_.id 
    left outer join
        working_schema.timetables timetablee2_ 
            on classentit0_.timetableid=timetablee2_.id 
    where
        classentit0_.id=?

内容的提问来源于stack exchange,提问作者Cross

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 08:50:28