【问题标题】:How to retrieve Username from customRevisionEntity如何从 customRevisionEntity 中检索用户名
【发布时间】:2015-07-28 05:30:25
【问题描述】:

我们正在使用 Hibernate-envers 3.6.3.Final 并且我正在使用 @Audited 注释正确生成表。我正在使用 CustomRevisionEntity 来存储用户信息,而 CustomRevisionListener 也存储了用户信息。但是如果我试图检索“用户名”,它会返回以下错误。

org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here
    at org.springframework.orm.hibernate3.SpringSessionContext.currentSession(SpringSessionContext.java:64) ~[spring-orm-3.2.6.RELEASE.jar:3.2.6.RELEASE]

我的 CustomRevisionEntity 类,

@Entity
@Table(name = "revision_info")
@RevisionEntity(CustomEnversListener.class)
public class CustomRevisionEntity implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue
    @RevisionNumber
    private int id;

    @RevisionTimestamp
    private long timestamp;

    private String username;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public long getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(long timestamp) {
        this.timestamp = timestamp;
    }

    @Column(name = "username")
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

CustomRevisionListener.java

public class CustomEnversListener implements RevisionListener {
    public void newRevision(Object revisionEntity) {
        CustomRevisionEntity customRevisionEntity = (CustomRevisionEntity) revisionEntity;
        Authentication authentication = SecurityContextHolder.getContext()
                .getAuthentication();
        customRevisionEntity.setUsername(authentication.getName());
    }
}

我的表如下,

mysql> select * from revision_info;
+----+---------------+-----------------+
| id | timestamp     | username        |
+----+---------------+-----------------+
|  1 | 1431693146030 | sky@test.com    |
|  2 | 1431693150805 | ram@test.com    |
|  3 | 1431693164895 | bobo@test.com   |
+----+---------------+-----------------+
3 rows in set (0.02 sec)

我可以使用以下代码使用“timeStamp”和“timeStamp”使用“rev”检索“rev”,

AuditReader reader = AuditReaderFactory.get(session);
Date timestamp = reader.getRevisionDate(rev);
Number revision = reader.getRevisionNumberForDate(timestamp);

但我无法使用休眠查询检索具有自定义字段“用户名”值的整行。

Criteria criteria = sessionFactory.getCurrentSession()
                .createCriteria(CustomRevisionEntity.class)
                .add(Restrictions.eq("id", rev));

上面的查询返回上面的错误。我该如何解决这个问题?? 如何从 revision_info 表中检索值?

我的错误的完整堆栈跟踪是,

org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here
    at org.springframework.orm.hibernate3.SpringSessionContext.currentSession(SpringSessionContext.java:64) ~[spring-orm-3.2.6.RELEASE.jar:3.2.6.RELEASE]
    at org.hibernate.impl.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:687) ~[hibernate-core-3.6.3.Final.jar:3.6.3.Final]
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) ~[spring-core-3.2.6.RELEASE.jar:3.2.6.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:701) ~[spring-aop-3.2.6.RELEASE.jar:3.2.6.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150) ~[spring-aop-3.2.6.RELEASE.jar:3.2.6.RELEASE]
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:91) ~[spring-aop-3.2.6.RELEASE.jar:3.2.6.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) ~[spring-aop-3.2.6.RELEASE.jar:3.2.6.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:634) ~[spring-aop-3.2.6.RELEASE.jar:3.2.6.RELEASE]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.6.0_31]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) ~[na:1.6.0_31]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.6.0_31]
    at java.lang.reflect.Method.invoke(Method.java:622) ~[na:1.6.0_31]
    at ognl.OgnlRuntime.invokeMethod(OgnlRuntime.java:870) ~[ognl-3.0.6.jar:na]
    at ognl.OgnlRuntime.callAppropriateMethod(OgnlRuntime.java:1293) ~[ognl-3.0.6.jar:na]
    at ognl.ObjectMethodAccessor.callMethod(ObjectMethodAccessor.java:68) ~[ognl-3.0.6.jar:na]
    at com.opensymphony.xwork2.ognl.accessor.XWorkMethodAccessor.callMethodWithDebugInfo(XWorkMethodAccessor.java:117) [xwork-core-2.3.20.jar:2.3.20]
    at com.opensymphony.xwork2.ognl.accessor.XWorkMethodAccessor.callMethod(XWorkMethodAccessor.java:108) [xwork-core-2.3.20.jar:2.3.20]
    at ognl.OgnlRuntime.callMethod(OgnlRuntime.java:1369) ~[ognl-3.0.6.jar:na]
    at ognl.ASTMethod.getValueBody(ASTMethod.java:90) ~[ognl-3.0.6.jar:na]
    at ognl.SimpleNode.evaluateGetValueBody(SimpleNode.java:212) ~[ognl-3.0.6.jar:na]
    at ognl.SimpleNode.getValue(SimpleNode.java:258) ~[ognl-3.0.6.jar:na]
    at ognl.Ognl.getValue(Ognl.java:494) ~[ognl-3.0.6.jar:na]
    at ognl.Ognl.getValue(Ognl.java:458) ~[ognl-3.0.6.jar:na]
    at com.opensymphony.xwork2.ognl.OgnlUtil$2.execute(OgnlUtil.java:309) ~[xwork-core-2.3.20.jar:2.3.20]
    at com.opensymphony.xwork2.ognl.OgnlUtil.compileAndExecute(OgnlUtil.java:340) ~[xwork-core-2.3.20.jar:2.3.20]
    at com.opensymphony.xwork2.ognl.OgnlUtil.getValue(OgnlUtil.java:307) ~[xwork-core-2.3.20.jar:2.3.20]
    at com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:423) ~[xwork-core-2.3.20.jar:2.3.20]
    at com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:287) ~[xwork-core-2.3.20.jar:2.3.20]
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:250) ~[xwork-core-2.3.20.jar:2.3.20]
    at org.apache.struts2.interceptor.DeprecationInterceptor.intercept(DeprecationInterceptor.java:41) ~[struts2-core-2.3.20.jar:2.3.20]

我的spring配置如下,

    <bean id="transactionManager"
              class="org.springframework.orm.hibernate3.HibernateTransactionManager">
            <property name="sessionFactory" ref="xxxSessionFactory"/>
    </bean>

    <tx:advice id="customRevisionEntityAdvice" transaction-manager="transactionManager">
            <tx:attributes>
                <tx:method name="*" read-only="false" propagation="REQUIRED"/>
            </tx:attributes>
    </tx:advice>

    <aop:config>
        <aop:pointcut id="crePointcut"
                      expression="execution(* bla.bla.CustomRevisionEntity.*(..))"/>
        <aop:advisor advice-ref="customRevisionEntityAdvice" pointcut-ref="crePointcut"/>
    </aop:config>

我的 application-content.xml 包含以下内容...

<bean id="auditEventListener" class="org.hibernate.envers.event.AuditEventListener" />

    <bean id="xxxSessionFactory"
          class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="annotatedClasses">
            <list>                  
                <value>bla.bla.domain.Myclass</value>
            </list>
        </property>

        <property name="eventListeners">
            <map>
                <entry key="post-insert" value-ref="auditEventListener"/>
                <entry key="post-update" value-ref="auditEventListener"/>
                <entry key="post-delete" value-ref="auditEventListener"/>
                <entry key="pre-collection-update" value-ref="auditEventListener"/>
                <entry key="pre-collection-remove" value-ref="auditEventListener"/>
                <entry key="post-collection-recreate" value-ref="auditEventListener"/>
            </map>
        </property>

【问题讨论】:

  • 这里的任何输入都非常感谢

标签: java hibernate hibernate-envers


【解决方案1】:

使用环境

您可以使用AuditReader查询CustomRevisionEntity

AuditReader auditReader = AuditReaderFactory.get(entityManager);

//Here you find the revision number that you want
Number revisionNumber = getRevisionNumber(auditReader);

//then you use the auditReader :-)
CustomRevisionEntity cRevEntity = auditReader.findRevision(
                CustomRevisionEntity.class, revisionNumber );

//Then you can just get your Username
String userName = cRevEntity.getUsername();

这是方法签名

 /**
 * A helper method; should be used only if a custom revision entity is used. See also {@link RevisionEntity}.
 * @param revisionEntityClass Class of the revision entity. Should be annotated with {@link RevisionEntity}.
 * @param revision Number of the revision for which to get the data.
 * @return Entity containing data for the given revision.
 * @throws IllegalArgumentException If revision is less or equal to 0 or if the class of the revision entity
 * is invalid.
 * @throws RevisionDoesNotExistException If the revision does not exist.
 * @throws IllegalStateException If the associated entity manager is closed.
 */
<T> T findRevision(Class<T> revisionEntityClass, Number revision) throws IllegalArgumentException,
        RevisionDoesNotExistException, IllegalStateException;

来自 Hibernate-envers 3.6.3.Final 源代码,这是在 AuditReaderImpl.java 第 193 行实现的:

@SuppressWarnings({"unchecked"})
public <T> T findRevision(Class<T> revisionEntityClass, Number revision) throws IllegalArgumentException,
        RevisionDoesNotExistException, IllegalStateException {
    checkNotNull(revision, "Entity revision");
    checkPositive(revision, "Entity revision");
    checkSession();

    Set<Number> revisions = new HashSet<Number>(1);
    revisions.add(revision);
    Query query = verCfg.getRevisionInfoQueryCreator().getRevisionsQuery(session, revisions);

    try {
        T revisionData = (T) query.uniqueResult();

        if (revisionData == null) {
            throw new RevisionDoesNotExistException(revision);
        }

        return revisionData;
    } catch (NonUniqueResultException e) {
        throw new AuditException(e);
    }
}

更新 - 缺少 Spring 配置

查看您的堆栈跟踪,您缺少一些 spring 事务配置。 要么使用声明性配置,要么使用注释。

声明式配置

您需要在配置 xml 中声明事务的使用,这是使用 AOP 切入点完成的。看这个example,你可以看到它首先设置了TransactionManager,它是DataSource,然后声明x.y.service.FooService的每个方法都需要一个事务

<!-- ensure that the above transactional advice runs for any execution
     of an operation defined by the FooService interface -->
<aop:config>
    <aop:pointcut id="fooServiceOperation" expression="execution(* x.y.service.FooService.*(..))"/>
    <aop:advisor advice-ref="txAdvice" pointcut-ref="fooServiceOperation"/>
</aop:config>

您提供的配置缺少 AOP 配置。为方便起见,您可以配置特定包中的每个类以使用事务。

<aop:config>
    <aop:pointcut id="fooServiceMethods" expression="execution(* x.y.service.*.*(..))"/>
    <aop:advisor advice-ref="txAdvice" pointcut-ref="fooServiceMethods"/>
</aop:config>

看到只是 expression="execution(* x.y.service.*.*(..))" 发生了变化。

使用@Transactional

幸运的是,Spring 提供了一种更简单的方法来声明 @Transactional 方法的使用,只需将类、接口或方法注释为 @Transactional

// the service class that we want to make transactional
@Transactional
public class DefaultFooService implements FooService {

    Foo getFoo(String fooName);

    Foo getFoo(String fooName, String barName);

    void insertFoo(Foo foo);

    void updateFoo(Foo foo);
}

之后我们需要配置spring来扫描我们的代码寻找@Transactional,以便在需要时生成正确的代理bean实例。

<!-- enable the configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="txManager"/><!-- a PlatformTransactionManager is still required -->

这是@Transactional 的complete example 和我的reference 用于有关事务的弹簧配置。

Hibernate 3 上的 Envers 配置

Hibernate 3 需要特殊配置才能与 Envers 一起使用,您需要将其添加到您的 persistence.xmlExample

<property name="hibernate.ejb.event.post-insert" value="org.hibernate.ejb.event.EJB3PostInsertEventListener,org.hibernate.envers.event.AuditEventListener" />
<property name="hibernate.ejb.event.post-update" value="org.hibernate.ejb.event.EJB3PostUpdateEventListener,org.hibernate.envers.event.AuditEventListener" />
<property name="hibernate.ejb.event.post-delete" value="org.hibernate.ejb.event.EJB3PostDeleteEventListener,org.hibernate.envers.event.AuditEventListener" />
<property name="hibernate.ejb.event.pre-collection-update" value="org.hibernate.envers.event.AuditEventListener" />
<property name="hibernate.ejb.event.pre-collection-remove" value="org.hibernate.envers.event.AuditEventListener" />
<property name="hibernate.ejb.event.post-collection-recreate" value="org.hibernate.envers.event.AuditEventListener" />

如果您没有persistence.xml 或hibernate.cfg.xml,并且您声明SessionFactory 并且它正常工作,您需要编辑您的spring 配置类似于this

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    ....
    <property name="eventListeners">
        <map>
            <entry key="post-insert" value-ref="auditListener"/>
            <entry key="post-update" value-ref="auditListener"/>
            <entry key="post-delete" value-ref="auditListener"/>
            <entry key="pre-collection-update" value-ref="auditListener"/>
            <entry key="pre-collection-remove" value-ref="auditListener"/>
            <entry key="post-collection-recreate" value-ref="auditListener"/>
        </map>
    </property>
    ...
</bean>

<bean id="auditListener" class="org.hibernate.envers.event.AuditEventListener"/>

【讨论】:

  • 感谢您的回复安德烈!仍然遇到同样的错误......“org.hibernate.HibernateException:没有绑定到线程的休眠会话,并且配置不允许在此处创建非事务性会话”
  • 嗯,那么这很可能是弹簧配置的问题。你能发布完整的堆栈跟踪吗?
  • 我在我的问题末尾添加了完整的堆栈跟踪...请看一下并提供您的想法...
  • 添加了一些关于 Spring 配置的说明。 @SST
  • 感谢您的及时回复@Andre!!!现在收到以下错误.. org.hibernate.envers.exception.AuditException: You need to install the org.hibernate.envers.event.AuditEventListener class as post insert, update and delete event listener.
【解决方案2】:

您缺少切入点定义,如 here 所述。

切入点可帮助您定义您希望将建议应用于何处。

【讨论】:

  • No Dragan.. 我也做了配置.. 仍然遇到同样的错误.. :( 请在我的问题中查看我的最后编辑。
  • 好的,很明显,导致问题的原因远不止这些,但无论如何它是一个缺失的部分。
【解决方案3】:

该错误最常见的原因是存在TransactionManager 并尝试执行未标记为@Transactional 的查询方法,或者可能是过于宽泛的&lt;tx:advice ... bean 定义。你能告诉你你的 spring 配置的相关部分吗?

TL;DR:尝试将@Transactional 添加到查询CustomRevisionEntity 的方法中,看看是否有帮助。如果是,请开始使用事务划分。

更新:您的 spring 配置需要所有方法的事务。您可以添加一个

<tx:method name="read*" read-only="true"/>

以匹配您的审核读取方法(将read* 更改为合理的内容,并确保"*" 不包罗万象)。您甚至可以将属性 propagation="SUPPORTS" 添加到此标记,以启用现有事务,如果您在这样的上下文中查询。

另外,您肯定在某处有TransactionInterceptor/auto-proxy 吗?

<bean id="txInterceptor" class="org.springframework.transaction.interceptor.TransactionInterceptor">
    <property name="transactionManager" ref="transactionManager"></property>
    <property name="transactionAttributeSource" ref="txAttributeSource"/>
</bean>

<bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
    <property name="beanNames">
        <list>          
            <value>yourServiceName<value>
            ...
        </list>
    </property>
    <property name="interceptorNames">
        <list>
            <idref local="txInterceptor"/>
        </list>
    </property>
</bean>

干杯,

【讨论】:

  • 嗨安德斯,我已经在方法的查询类中添加了@Transactional,并且还在我的 application-context.xml 中配置了
  • 我已经在我的问题结束时发布了我的 spring 配置。请查看并提供您的建议
猜你喜欢
  • 2012-01-06
  • 2013-12-11
  • 2018-03-16
  • 2013-02-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多