0

I have entities User and Position. Many users can have one position.

When I tried to delete position, users with this position also were deleted.

Then i tried to set null to position of users and I got this exception:

java.sql.SQLIntegrityConstraintViolationException: Column 'position_id' cannot be null.

User entity:

@Data
@Entity
public class User {

    @Id
    @Column(name = "user_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name="position_id")
    private Position position;
}

Position entity:

@Data
@Entity
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Position {

    @Id
    @Column(name = "position_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "position_name")
    private String name;

    @OneToMany(mappedBy = "position", fetch = FetchType.EAGER)
    @OnDelete(action = OnDeleteAction.NO_ACTION)
    @JsonIgnore
    private List<User> users;
}

PositionService delete method:

@Service
@Slf4j
public class PositionServiceImpl implements PositionService {

    private final PositionRepository positionRepository;

    @Autowired
    public PositionServiceImpl(PositionRepository positionRepository) {
        this.positionRepository = positionRepository;
    }

    @Override
    public void delete(Long id) {
        Position position = positionRepository.findPositionById(id);
        for(User user : position.getUsers()) {
            user.setPosition(null);
        }
        positionRepository.deleteById(id);
        log.info("IN delete - {} position deleted", id);
    }
 }

RestController:

@DeleteMapping(value = "positions/delete/{id}")
public ResponseEntity deletePosition(@PathVariable(name = "id") Long id) {
    Position position = positionService.getById(id);
    if(position == null) {
        return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
    }
    positionService.delete(id);
    return new ResponseEntity<>(HttpStatus.OK);
}
Vladyslav
  • 1
  • 2
  • 1
    see if this gives you ideas https://stackoverflow.com/questions/8243400/on-delete-set-null-in-hibernate-in-onetomany – JCompetence Feb 17 '22 at 15:18
  • what do you want to happen exactly if you have a null constraint on the position_id column in user? It has to reference something according to your database schema, so you can't just remove a position on your users without giving them a new one. How was this schema created? – Chris Feb 17 '22 at 16:43

0 Answers0