[英]Hibernate / Spring Data - get executed sql queries count
我正在处理演示文稿,其中我想显示在使用和不使用自定义查询的deleteByPost()
方法之间执行的 sql 查询数量的差异。 我期望没有自定义查询的方法可以执行 10001 个删除查询,而只有 2 个。
我知道 Hibernate 统计信息 object 及其方法。 我期待其中一个名为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
的钩子。 您可以扩展此类并在onPrepareStatement
挂钩中添加逻辑以计算查询。
查看库代码以了解如何配置迭代器。
onPrepareStatement
方法现已弃用,并在新的 Hibernate 6 版本中删除。 检查 SQL 的新方法是实现StatementInspector
。
我写了一个小库( https://github.com/Lemick/hibernate-query-asserts ),它可以断言 Spring 测试中 Hibernate 生成的类型(SELECT,INSERT,..)的 SQL 查询的计数,这样,只要测试中的 SQL 语句发生变化,您就会收到警告,并防止 N+1 选择。 如果你想知道这是如何实现的,你可以看看这里的项目。
演示目的的测试示例:
@Test
@Transactional
@AssertHibernateSQLCount(inserts = 3)
void create_two_blog_posts() {
BlogPost post_1 = new BlogPost("Blog post 1");
post_1.addComment(new PostComment("Good article"));
post_1.addComment(new PostComment("Very interesting"));
blogPostRepository.save(post_1);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.