【问题标题】:Spring JPA one to many denormalized count fieldSpring JPA 一对多非规范化计数字段
【发布时间】:2016-07-09 21:19:26
【问题描述】:

我有两个实体,书籍和评论,是一对多的关系(一本书可以有很多 cmets)。我希望能够列出关于一本书的书籍和 cmets 的数量。我希望它非规范化,这意味着书籍实体将有一个计数器,其中包含该书的 cmets 数量,并且每次输入评论时都会更新(只是玩这个概念,无需在这里讨论非规范化的需要)。

我认为(如果我错了,请纠正我)这可以通过数据库中的触发器轻松完成(每当创建新评论时,将 books 表中的计数器更新为相应的 bookId),但为了学习我想通过 JPA 来做,如果有意义的话。

到目前为止我所知道的://省略了一些注释,只是一般信息

博克斯实体:

@Entity 
public class Books {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String title;
    private String author;
    private Long numComments;

  // getters and setters...
}

评论实体:

@Entity
public class Comments {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String comment;
    private Long authorId;
    private Long bookId;

  // getters and setters...
}

图书存储库:我在此处添加了一个查询来执行更新

/**
 * Spring Data JPA repository for the Books entity.
 */
public interface BooksRepository extends JpaRepository<Books,Long>         {
@Modifying
@Query("UPDATE Books v SET v.numComments = v.numComments + 1 WHERE v.id = :bookId")
int updateCounter(@Param("bookId")Long bookId);

}

现在的问题是:下一步是什么?我想我可以将用@PostPersist 注释的Books 实体的更新放在实体Comments 的方法中,但到目前为止我还没有成功。我可以想象这样的事情:

    @PostPersist  //This function in the entity Comments
    protected void updateBooks() {
        //Likely some call to the repository here that updates the count
        //   in books the info we have from current entity.
    }

知道如何做到这一点吗?关于 JPA 中这种非规范化的一些最佳实践?最好使用数据库触发器?

【问题讨论】:

    标签: spring jpa denormalization


    【解决方案1】:

    spring没有管理你的实体类,你的想法是可能的,但是你必须在enttiy类中注入BooksRepository然后留在你得到Nullpointerexception,因为spring没有管理实体类,你的BooksRepository没有初始化的原因,试试看这个发布Bean injection inside a JPA @Entity 并在之后注释实体类@Configurable

    试试这个

    @PostPersist 
    protected void updateBooks(Comments comment) {
    
        int totalComment = BooksRepository.updateCounter(comment.getBookId());
    
        System.out.println(totalComment); // see totalComment in console
    }
    

    但在插入评论时调用updateCounter 后服务类的方法很好

    CommendService 中的示例:在调用 updateCounter 后尝试插入推荐时

        if(comment.getBookId() != null) //Simple Control
         {
    
            CommentRepository.save(comment);
            BooksRepository.updateCounter(comment.getBookId());
        }
    

    【讨论】:

      猜你喜欢
      • 2017-08-19
      • 2017-10-28
      • 2018-05-07
      • 2021-09-07
      • 1970-01-01
      • 1970-01-01
      • 2013-01-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多