Usage of P6Spy with datasource in Spring applicati

2019-02-10 22:10发布

问题:

I am using Hibernate 4, Spring 3, JSF 2.0 and Weblogic 10.3.6 as server.

I have created datasource on Weblogic server and in applicationContext.xml I have defined datasource as

<!-- Data Source Declaration -->    
    <bean id="DataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName" value="jdbc/​myDS"/>   
</bean>

If I would want to use the P6Spy for logging SQL parameters, how can and where I should add the following in applicationcontext.xml?

  <property name="hibernate.connection.driver_class">com.p6spy.engine.spy.
  P6SpyDriver</property>

Any help is highly appreciable.

Thanks

回答1:

The easiest way to integrate p6spy using spring is to use the P6DataSource class. The P6DataSource class is just a proxy for the real data source. This lets you obtain the real data source using any of the spring data source factory implementations.

<bean id="dataSource" class="com.p6spy.engine.spy.P6DataSource">
  <constructor-arg>
    <bean id="DataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
      <property name="jndiName" value="jdbc/​myDS"/>   
    </bean>
  </constructor-arg>
</bean>

If you are using an XADatasource, just change the classname to P6ConnectionPoolDataSource as shown below. Note: P6ConnectionPoolDataSource implements the ConnectionPoolDataSource and XADataSource interfaces.

<bean id="dataSource" class="com.p6spy.engine.spy.P6ConnectionPoolDataSource">
  <constructor-arg>
    <bean id="DataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
      <property name="jndiName" value="jdbc/​myDS"/>   
    </bean>
  </constructor-arg>
</bean>


回答2:

You need to create bean of session factory in applicationContext.xml file as follows:

<bean id="sessionFactory"
    class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource">
            <ref bean="dataSource" />
        </property>
    </bean>
    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.p6spy.engine.spy.
  P6SpyDriver" />
        <property name="url" value="jdbc\:mysql\://localhost\:3306/testdb" />
        <property name="username" value="my_username" />
        <property name="password" value="my_password" />
    </bean>

Please refer to: http://www.mkyong.com/hibernate/how-to-display-hibernate-sql-parameter-values-solution/ for more about P6Spy library.

We can omit "dataSource" bean and directly write properties. Ref: how to configure hibernate config file for sql server