[英]Spring JpaRepository doesn't delete row in table
我正在使用 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;
}
您可以尝试做类似的关系并检查它是否有效并根据您的要求进行改造。
在您的控制器中,尝试首先使用“id”获取记录
Post post = postRepository.findById(id)
然后使用返回 Post 对象并调用 delete。 不需要创建这样的原生查询,JpaRepository (CrudRepository) 有你需要的基本内置函数
postRepository.delete(post)
使用 Hibernate 时,无论何时要执行任何操作,都可以将对象放入会话中。
因此,尝试加载您的 User 对象并使用 user.getListofPosts().remove(post.getId()) 删除帖子。
之后,更新您的用户对象。
这应该在用@Transactional 注释的操作中完成。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.