java - 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 并且不删除。我试过添加@Query
PostRepository
@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 出了点问题,但不明白到底是什么
解决方案
您可以尝试在@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;
}
您可以尝试做类似的关系并检查它是否可以正常工作并根据您的要求进行改造。
推荐阅读
- javascript - 将两个数组组合成键值对,如果键已经存在,则添加值
- laravel - 有没有办法保护 laravel tinker?
- spring-boot - 如何在没有xml的情况下使用FF4J获取java中的特性
- c - OpenGL并显示灰度图像
- javascript - 如何编辑从s中的字符串转换而来的数组中的特定数字
- java - 当拦截器没有默认构造函数时,如何在 Google Guice 中绑定拦截器?
- typescript - tsconfig 中 rootDir 和 baseUrl 的区别
- javascript - SCORM: SecurityError: Blocked a frame with origin from access a cross-origin frame FOR SAME ORIGIN
- python - 向 python 中调用的 nodeJS 进程发送 Ctrl-C 命令
- javascript - 构建期望第一个字符大写的 Javascript 正则表达式,其余字符不区分大小写