问题描述
我正在使用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而不是不删除。我尝试在PostRepository中添加@Query
@Modifying(clearAutomatically = true,flushAutomatically = true)
@Query(value = "DELETE FROM post WHERE id = ?1",nativeQuery = true)
void deleteById(long postId);
尝试在用户中添加@OneToMany
。尝试使用其他FetchType,但没有帮助。
PostRepository:
@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",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注释的操作中完成。