Deng
Deng

Reputation: 178

I want to also save parent entity when save child entity by useing Spring data JPA

Here is the entity code:

@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;
}

Here is the save code:

@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));
    }
}

As above, when I try to save a user, It will be auto-save a student, but in the t_student table, the column c_user_id is empty. so I have to write the code user.getStudent().setUser(user) to update the column c_user_id.

so why? and what should I do to let the column c_user_id be auto-filled on saving user

ps: I don't want to change the mappedBy relation to Student, I know that could work, but I think a User can be a student, also can be another character, so if I add some other character, it will modify t_user table. This causes the table to become more and more bloated

Upvotes: 0

Views: 275

Answers (1)

Jens Schauder
Jens Schauder

Reputation: 81862

The Student gets persisted. But you specified that the Student is responsible for maintaining the relationship between Student and User, and since Student.user is null this gets persisted in the database.

Therefore Hibernate is literally doing what you told it to do.

Upvotes: 1

Related Questions