首页 > 解决方案 > Spring JpaRepository 不会删除表中的行

问题描述

我正在使用 postgresql 并且有 2 个类。用户:

@Entity
@Table(name="usr") //
public class User implements UserDetails {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
}

并发布

@Entity
public class Post {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "user_id")
    private User author;
}

当我尝试通过 id Hibernate 删除帖子时,将除 user_id 之外的所有字段设置为 null 并且不删除。我试过添加@QueryPostRepository

@Modifying(clearAutomatically = true, flushAutomatically = true)
@Query(value = "DELETE FROM post WHERE id = ?1", nativeQuery = true)
void deleteById(long postId);

尝试添加@OneToMany用户。尝试了不同的 FetchType,但没有任何帮助。

后存储库:

@Repository
public interface PostRepository extends JpaRepository<Post, Long> {

}

像这样删除帖子:

@DeleteMapping("/{id}")
public String blogPostDelete(@PathVariable("id") long id) {
    postRepository.deleteById(id);
    return "redirect:/blog";
}

我几乎确定@ManyToOne 出了点问题,但不明白到底是什么

标签: javapostgresqlspring-boothibernatemany-to-one

解决方案


您可以尝试在@Transactional自定义查询上方添加注释。
如果结果仍然相同,您可以在我的工作代码中找到一些东西。删除工作:

家长:

@Entity
@Table(name = "users")
public class EntityUser {

    @Id
    @Column(name = "uuid_user", length = 16, unique = true, nullable = false)
    private final UUID uuid = UUID.randomUUID();

    @OneToMany(targetEntity=EntityNote.class, mappedBy = "owner", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private List<EntityNote> noteList = new ArrayList<>();
}

和孩子:

@Entity
@Table(name = "notes")
public class EntityNote {
   
    @Id
    @Column(name = "uuid_note", length = 16, unique = true, nullable = false)
    private UUID uuid = UUID.randomUUID();
   
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "owner")
    private EntityUser owner;
}

您可以尝试做类似的关系并检查它是否可以正常工作并根据您的要求进行改造。


推荐阅读