1

Тема: JpaRepository deleteById не видаляє з бази даних

Привіт, виникла проблема з моєю crud апкою, deleteById не видаляє з бази, виконуючи лише select та повертає на сторінку all начебто виконано успішно, проблема виникає на всіх ентітях які існують(Employee та FiredEmployee), всі інші методи працюють. Пробував без dto, rest імплементації, але всеодно не працює, прописав нативно запит в репозиторії, але також не допомогло.  Буду вдячний за будь-яку допомогу)

@Service
public class EmployeeServiceImpl implements EmployeeService {
    
    @Autowired 
    private EmployeeRepository employeeRepository;
    
    @Autowired
    private RoleRepository roleRepository;
    
    @Autowired
    private PasswordEncoder passwordEncoder;
    
    @Override
    public Employee saveAndFlush(EmployeeDto employeeDto) {
        Employee employee = findByEmail(employeeDto.getEmail());
        
        if (employee == null){
            employee = new Employee();
            employee.setPassword(passwordEncoder.encode(employeeDto.getPassword()));
            
            Role role = roleRepository.findByName("ROLE_ADMIN");
        
            if(role == null){
                role = checkRoleExist();
            }
            
            employee.setRoles(Arrays.asList(role));
        }
        employee.setId(employeeDto.getId());
        employee.setFirstName(employeeDto.getFirstName());
        employee.setLastName(employeeDto.getLastName());
        employee.setBirthDate(employeeDto.getBirthDate());
        employee.setPhoneNumber(employeeDto.getPhoneNumber());
        employee.setDepartment(employeeDto.getDepartment());
        employee.setEmail(employeeDto.getEmail());
        employee.setEnabled(employeeDto.getEnabled());
        employee.setConfirmationToken(employeeDto.getConfirmationToken());
        return employeeRepository.save(employee);
    }

    @Override
    public Employee findByEmail(String email) {
        return employeeRepository.findByEmail(email);
    }
    
    @Override
    public void deleteById(Long id) {
        employeeRepository.deleteById(id);
    }

    @Override
    public List<EmployeeDto> findAll() {
        List<Employee> employees = employeeRepository.findAll();
        return employees.stream()
                .map((employee) -> convertEntityToDto(employee))
                .collect(Collectors.toList());
    }

    private EmployeeDto convertEntityToDto(Employee employee){
        EmployeeDto employeeDto = new EmployeeDto();
        employeeDto.setId(employee.getId());
        employeeDto.setFirstName(employee.getFirstName());
        employeeDto.setLastName(employee.getLastName());
        employeeDto.setPhoneNumber(employee.getPhoneNumber());
        employeeDto.setBirthDate(employee.getBirthDate());
        employeeDto.setDepartment(employee.getDepartment());
        employeeDto.setEmail(employee.getEmail());
        employeeDto.setEnabled(employee.getEnabled());
        employeeDto.setConfirmationToken(employee.getConfirmationToken());
        return employeeDto;
    }

    private Role checkRoleExist() {
        Role role = new Role();
        role.setName("ROLE_ADMIN");
        return roleRepository.save(role);
    }
 

    @Override
    public Optional<Employee> findById(Long id) {
        return employeeRepository.findById(id);
    }

}
@PostMapping("/delete/{id}")
    public String postDelete(@PathVariable Long id) {
        employeeService.deleteById(id);
            
        return "redirect:/registered/all";
    }
@DeleteMapping
    ResponseEntity<Map<String, Object>> delete(@PathParam("id") Long id) {
        Map<String, Object> answer = new HashMap<>();
        Optional<Employee> optionalEmployee = Optional.empty();
        if (id != null)
            optionalEmployee = employeeService.findById(id);

        if (optionalEmployee.isEmpty()) {
            answer.put("result", "Error");
            answer.put("body", new RuntimeException("Couldn't find user with id - " + id));
            return new ResponseEntity<>(answer, HttpStatus.BAD_REQUEST);
        } else {
            employeeService.deleteById(id);
            answer.put("result", "SUCCESSFUL");
            answer.put("body", "User " + id + " has been deleted");
            return new ResponseEntity<>(answer, HttpStatus.ACCEPTED);
        }
    }
 
@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long>{
    Employee findByEmail(String email);
    
    EmployeeDto findByConfirmationToken(String confirmationToken);

}
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Entity
@Table(name = "employees")
public class Employee {
 
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id; 
    
    @Column(name = "first_name", nullable = false)
    private String firstName;
    
    @Column(name = "last_name", nullable = false)
    private String lastName;
     
    @Column(name = "department", nullable = false)
    private String department;
    
    @Column(name = "birth_date", nullable = false)
    private String birthDate;
    
    @Column(name = "phone_number", nullable = false)
    private String phoneNumber;

    @Column(name = "email", nullable = false, unique = true)
    private String email;
    
    @Column(name = "password", nullable = false)
    private String password;

    @Column(name = "enabled", nullable = false)
    private Boolean enabled;
    
    @Column(name = "confirmation_token")
    private String confirmationToken;
    
    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(
            name="employees_roles",
            joinColumns={@JoinColumn(name="EMPLOYEE_ID", referencedColumnName="ID")},
            inverseJoinColumns={@JoinColumn(name="ROLE_ID", referencedColumnName="ID")})
    private List<Role> roles = new ArrayList<>();
    
}

2

Re: JpaRepository deleteById не видаляє з бази даних

Яка БД? Що в логах? Чи є доступ до коду на GitHub?

3

Re: JpaRepository deleteById не видаляє з бази даних

tan написав:

Яка БД? Що в логах? Чи є доступ до коду на GitHub?

Дякую за відповідь, проблему вже вирішив, були проблеми з thymeleaf формою.