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