使用 Entity Listener 测量数据库操作所花费的时间

Measure the time database actions take with an Entity Listener

基本上我需要计算对象被持久化、更新等的次数。使用 @PostPersist@PostUpdate 等等。

但我还需要知道这些存储操作需要多长时间(只是全部),有没有办法使用(默认)实体监听器来完成?

您可以激活休眠统计信息:通过persistence.xml

中的配置,通过命令行属性将hibernate.generate_statistics设置为true
...
<properties>
    ...
    <property name="hibernate.generate_statistics" value="true"/>   
<properties>

并添加到您的日志记录配置

<logger name="org.hibernate.stat" level="DEBUG" />

这会告诉您每个会话执行了多少 SQL 个语句以及需要多长时间

顺便说一句:内部是由 org.hibernate.engine.internal.StatisticalLoggingSessionEventListener

完成的

我相信实现此目标的更好方法是使用 AOP,拦截您想要测量的方法并做任何您想做的事情。 Spring AOP 似乎很适合这个。

我知道它与Entity Listener无关,但它只是一个不同的ideia =)

带示例的文档:http://docs.spring.io/autorepo/docs/spring-framework/3.2.x/spring-framework-reference/html/aop-api.html