Удаление Spring Boot JPA возвращает 200ок, но не удаляет из БД - PullRequest
0 голосов
/ 01 апреля 2020

Здравствуйте, я хочу удалить записи из базы данных. Но есть некоторая проблема.

Диаграмма БД

DB diagram

ACCOUNT Entity

@Entity
@Table(name = "compte", schema = "vshop_schema")
public class Account {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private int id;

    @Column(name = "email", nullable = false)
    @Email
    @NotEmpty()
    private String email;

    @Column(name = "pass", nullable = false)
    @NotEmpty
    @Size(min = 6)
    @PasswordFormat
    private String password;

    @Transient
    private String passwordConfirm;

    @Column(name = "active")
    private boolean active = true;

    @OneToOne(fetch = FetchType.EAGER, optional = false, cascade = CascadeType.ALL)
    @JoinColumn(name = "utilisateur_id")
    private User user;

    @ManyToOne(fetch=FetchType.EAGER, cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
    @JoinColumn(name = "role_id")
    @JsonBackReference
    private Role role;

    public Account() {
    }

    getters/setters

USER Entity

@Entity
@Table(name = "utilisateur", schema = "vshop_schema")
@JsonIgnoreProperties("account")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private int id;

    @Column(name = "user_name")
    @NotNull
    @Pattern(regexp = "^[a-zA-Z0-9._-]{3,}$", message = "Ce n'est pas un pseudo")
    private String userName;


    @Column(name = "date_inscription")
    @CreationTimestamp
    @JsonFormat(pattern="dd/MM/yyyy")
    private Date dateRegistration;

    @OneToOne(mappedBy = "user", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    private Account account;

    @OneToOne(mappedBy = "user", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    private UserInfo userInfo;

    public User() {
    }

    getters/setters

Служба учетных записей

@Override
@Transactional
public void deleteAccount(int userId) {
    accountRepository.deleteAccountByUserId(userId);
}

и RestController

@RestController
@RequestMapping("/api")
public class AccountRestController {

    @Autowired
    private AccountRepository repository;

    ...
    @DeleteMapping("/users/{userId}/accounts")
    public String deleteAccount(@PathVariable int userId) {
            accountService.deleteAccount(userId);
            return "Deleted Succefully";
    }
}

Я пытался удалить объект с accountRepository.delete(account) - тот же результат accountRepository.deleteById(accountById) - тот же результат

Я добавил @Transactional только для метода удаления, потому что Spring спросил меня об этом.

{
    "status": 500,
    "message": "No EntityManager with actual transaction available for current thread - cannot reliably process 'remove' call; nested exception is javax.persistence.TransactionRequiredException: No EntityManager with actual transaction available for current thread - cannot reliably process 'remove' call",
    "timestamp": 1585730989245
}

Мне кажется, у меня проблемы в отношениях между сущностями. Спасибо.

ОБНОВЛЕНИЕ: AccountRepository

public interface AccountRepository extends JpaRepository<Account, Integer> {
    Account findByEmail(String email);

    Account findByUser(User user);

    @Query(value = "select email from vshop_schema.compte u where u.utilisateur_id = ?1", nativeQuery = true)
    String findEmailByUserId(int id);

    void deleteAccountByUserId(int id);
}

ОБНОВЛЕНИЕ: Другие операции (Сохранить, Обновить, Получить) работают хорошо.

1 Ответ

0 голосов
/ 01 апреля 2020

Я нашел решение. Я поместил пользовательский запрос выше метода deleteById

@Modyfing
@Query("delete from /name-of-table/ n where n./column-name/ = ?1", nativeQuery=true)
void deleteById (int id);

Но все равно я не понял, почему он не работает без пользовательских запросов с методами удаления по умолчанию или deleteById.

...