java - Hibernate/Spring Data - 获取执行的 sql 查询计数

标签 java hibernate spring-data-jpa

我正在做演示,我想在其中显示 deleteByPost() 之间执行的 sql 查询数量的差异有和没有自定义查询的方法。我期待没有自定义查询的方法执行 10001 个删除查询,而只有 2 个。

我知道 Hibernate Statistics对象及其方法。我在期待其中一个,名为 getQueryExecutionCount() , 返回对 db 执行的 sql 查询的数量,但我得到的始终是 0。

如果有人想知道是否确实启用了 hibernate 统计信息,因为我在其他属性上获得了正确的数字,例如已删除实体的计数。

下面是一个完整的示例,显示了我想要完成的工作。

有没有办法使用 Statistics 获取生成和执行的查询的数量?或任何其他机制?目前我正在查看日志( hibernate.show_sql )并计算打印的查询,但对我来说似乎是错误的。

package example5

import org.hibernate.SessionFactory
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertAll
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.data.jpa.repository.Modifying
import org.springframework.data.jpa.repository.Query
import org.springframework.data.jpa.repository.config.EnableJpaRepositories
import org.springframework.data.repository.PagingAndSortingRepository
import org.springframework.data.repository.query.Param
import org.springframework.stereotype.Repository
import org.springframework.stereotype.Service
import org.springframework.test.context.junit.jupiter.SpringJUnitJupiterConfig
import org.springframework.transaction.annotation.EnableTransactionManagement
import org.springframework.transaction.annotation.Transactional
import javax.persistence.*

// ENTITIES

@Entity
@Table(name = "posts")
class Post(
        @Id
        @Column(name = "id")
        @GeneratedValue(strategy = GenerationType.SEQUENCE)
        var id: Long? = null,

        @Version
        @Column(name = "version")
        var version: Long? = null
)

@Entity
@Table(name = "comments")
class Comment(
        @Id
        @Column(name = "id")
        @GeneratedValue(strategy = GenerationType.SEQUENCE)
        var id: Long? = null,

        @Version
        @Column(name = "version")
        var version: Long? = null,

        @JoinColumn(name = "post_id")
        @ManyToOne(fetch = FetchType.LAZY)
        var post: Post? = null
)


// REPOSITORIES

@Repository
interface PostRepository : PagingAndSortingRepository<Post, Long>

@Repository
interface CommentRepository : PagingAndSortingRepository<Comment, Long> {

    @Modifying
    @Query("delete from Comment c where c.post = :post")
    fun deleteByPost(@Param("post") post: Post)
}


// SERVICES

interface PostService {

    fun delete(post: Post)
}

@Service
open class PostServiceImpl(
        @Autowired
        val postRepository: PostRepository,

        @Autowired
        val commentRepository: CommentRepository
) : PostService {
    @Transactional
    override fun delete(post: Post) {
        commentRepository.deleteByPost(post)
        postRepository.delete(post)
    }

}

// CONFIGURATION

@EnableJpaRepositories(basePackages = ["example5"])
@EnableTransactionManagement
@SpringBootApplication(scanBasePackages = ["example5"])
open class FrameworkApplication


// TESTS

@SpringJUnitJupiterConfig(classes = [FrameworkApplication::class])
class Example5(
        @Autowired
        val postService: PostService,

        @Autowired
        val postRepository: PostRepository,

        @Autowired
        val commentRepository: CommentRepository,

        @Autowired
        val emFactory: EntityManagerFactory
) {

    @AfterEach
    fun cleanUp() {
        commentRepository.deleteAll()
        postRepository.deleteAll()
    }

    @Test
    fun testDelete() {
        //given
        var post = Post()
        post = postRepository.save(post)
        val comments = mutableListOf<Comment>()
        for (i in 1..10000) {
            val comment = Comment()
            comment.post = post
            comments.add(comment)
        }
        commentRepository.save(comments)

        val sessionFactory = emFactory.unwrap(SessionFactory::class.java)
        val statistics = sessionFactory.statistics

        //then
        statistics.clear()
        postService.delete(post)

        val executedQueryCount = statistics.queryExecutionCount


        //then
        assertAll(
                { assertEquals(0, postRepository.count()) },
                { assertEquals(0, commentRepository.count()) },
                { assertEquals(2, executedQueryCount) }
        )
    }

}

最佳答案

库 Spring Hibernate Query Utils ( https://github.com/yannbriancon/spring-hibernate-query-utils ) 提供了一个查询计数器,您可以使用它来检查生成的查询数量。

如果你更喜欢自己做,Hibernate 提供了一个类 EmptyInterceptor包含一个名为 onPrepareStatement 的钩子(Hook).
您可以扩展此类并在 onPrepareStatement 中添加逻辑钩子(Hook)来计算查询。

查看库代码以了解如何配置迭代器。

关于java - Hibernate/Spring Data - 获取执行的 sql 查询计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59125188/

相关文章:

java - 通过Socket传输大数据

java - 将特定范围的数字添加到数组

java - 具有接口(interface)属性的 JPA 实体,这可能吗?

java - 为什么我在 Java 中收到 NoClassDefFoundError 错误?

java - Android Studio Gradle 项目 "Unable to start the daemon process/initialization of VM"

java - weblogic.deployment.PersistenceUnitInfoImpl.getSharedCacheMode()Ljavax/persistence/SharedCaheMode

mysql - Java JPA - 持久连接表

java - 始终对 JPA @Id 使用原始对象包装器而不是原始类型?

mysql - 如何计算通过 docker 动态部署的 MySQL 数据源中的可用空间

java - 从maven spring mvc创建表时出现问题