【问题标题】:I want to also save parent entity when save child entity by useing Spring data JPA我还想在使用 Spring data JPA 保存子实体时保存父实体
【发布时间】:2021-09-17 06:40:52
【问题描述】:

这里是实体代码:

@Entity
@Table(name = "t_user")
public class User{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    //omit other fields

    @OneToOne(cascade = javax.persistence.CascadeType.ALL, mappedBy = "user")
    private Student student;
}
@Entity
@Table(name = "t_student")
public class Student{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    @OneToOne
    @JoinColumn(name = "c_user_id", referencedColumnName = "id", foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT), columnDefinition = "INT COMMENT 'user number'")
    private User user;
}

这是保存代码:

@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl implements UserService {
    @Autowired    
    private final UserRepository userRepository;

    @Autowired  
    private final PasswordEncoder pwdEncoder;

    @Override
    public Optional<UserBody> add(UserParam param) {
        User user = User.from(param);
        if(userRepository.countByName(user.getName()) > 0){
            throw new BusinessException("user already exists");
        }
        user.setPassword(pwdEncoder.encode(param.getPassword()));
        
        userRepository.save(user);
        user.getStudent().setUser(user);  // do this for update the column `c_user_id` of student table
        return Optional.of(UserBody.from(user));
    }
}

如上所述,当我尝试保存用户时,它会自动保存学生,但在t_student 表中,c_user_id 列是空的。所以我必须编写代码user.getStudent().setUser(user) 来更新列c_user_id

那为什么?以及我应该怎么做才能让c_user_id 列在保存用户时自动填充

ps:我不想改变 mappedBy 与 Student 的关系,我知道这可以工作,但我认为 User 可以是学生,也可以是另一个角色,所以如果我添加一些其他角色,它将修改t_user 表。这导致表格越来越臃肿

【问题讨论】:

    标签: java spring hibernate spring-data-jpa


    【解决方案1】:

    Student 被持久化。但是您指定了Student 负责维护StudentUser 之间的关系,并且由于Student.usernull,因此它会保留在数据库中。

    因此,Hibernate 确实是按照您的指示去做。

    【讨论】:

    • 哦,我明白了。因为Student.user不能自动设置,所以双向关系不能这样做
    猜你喜欢
    • 2022-11-29
    • 2019-09-30
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    • 2017-03-15
    • 1970-01-01
    • 1970-01-01
    • 2013-05-09
    相关资源
    最近更新 更多