Announcement Announcement Module
Collapse
No announcement yet.
use of Spring/Hibernate with different user connections?? Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • use of Spring/Hibernate with different user connections??

    Hello,

    I'm trying to use Spring framework with Hibernate. Up until now I am using the HibernateTemplate to call Hibernate methods, and this works perfectly. I need now to have different user connections (db views are based on user access). How could I use HibernateTemplate then? could i use a sessionfactory and create sessions using different connections?
    thanks a lot

  • #2
    Take a look at org.springframework.jdbc.datasource.UserCredential sDataSourceAdapter.
    HTH

    Comment


    • #3
      Thanks Omar for your reply.

      I have been trying to use the class you mentioned and i'm having problems to getConnection(username, passwd) from the code. I have an exception that mentions PoolingDataSource.getConnection. It's probably that i'm not using the right procedure to do that.

      Can you tell me how should i get connections from the source code? Should i instanciate myDataSource? myTargetDataSource? should i retrieve them from the Application Context?
      I'm lost and I can 't figure out how to create Sessions with different connections...help!!!

      thanks a lot

      Comment


      • #4
        Basically, you do not need to change the configuration of your dataSource, let's call it targetDataDource in the following example (DataSources retrieved from JNDI may be used in the same way):
        Code:
          <bean id="targetDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
            <property name="driverClassName"><value>oracle.jdbc.driver.OracleDriver</value></property>
            <property name="url"><value>jdbc&#58;oracle&#58;thin&#58;@localhost&#58;1521&#58;ORCL</value></property>
          </bean>
        now we configure the UserCredentialsDataSourceAdapte:
        Code:
         <bean id="dataSource" class="org.springframework.jdbc.datasource.UserCredentialsDataSourceAdapter">
           <property name="targetDataSource"><ref bean="targetDataSource"/></property>
           <property name="username"><value>taha</value></property>
           <property name="password"><value>manager</value></property>
         </bean>
        and the Hibernate SessionFactory:
        Code:
          <bean id="sessionFactory" class="org.springframework.orm.hibernate.LocalSessionFactoryBean">
            ....
            <property name="dataSource"><ref local="dataSource"/></property>
          </bean>
        You do not need to use getConnection() since Hibernate will do it behind the scene. You must, however call
        Code:
          UserCredentialsDataSourceAdapter ds = &#40;UserCredentialsDataSourceAdapter&#41; context.getBean&#40;"dataSource&#41;;
          ds.setCredentialsForCurrentThread&#40;user, password&#41;;
        before each call to your dao methods to switch the user. You may also call
        Code:
          ds.removeCredentialsFromCurrentThread&#40;&#41;;
        to remove the credentials and use the statically specified ones.

        PS: you can specify / remove credentials using an Interceptor and hook it into your TransactionProxyFactoryBean using preInterceptors.
        HTH

        Comment


        • #5
          Hello Omar,
          I have tried for several days to make the configuration you sent me work. I have an error when i deploy the aplication and it's referred to the database connection. Maybe you or someone can give me a hand, i don't know what else to change..
          I'm deploying my web application in weblogic 8.1 and my applicationContext looks like this:

          <bean id="myTargetDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
          <property name="driverClassName"><value>oracle.jdbc.driver.O racleDriver</value></property>
          <property name="url"><value>jdbc:oracle:thin:@zus44x-0202.tszrh.xxxx.com:1521ZHXXX01</value></property>
          </bean>

          <bean id="dataSource" class="org.springframework.jdbc.datasource.UserCre dentialsDataSourceAdapter">
          <property name="targetDataSource"><ref bean="myTargetDataSource"/></property>
          <property name="username"><value>bbb</value></property>
          <property name="password"><value>bbbb</value></property>
          </bean>

          <!-- Hibernate SessionFactory Definition -->
          <bean id="sessionFactory" class="org.springframework.orm.hibernate.LocalSess ionFactoryBean">
          <property name="mappingResources">
          <list>
          <value>com/clr/backend/businessobject/FeedStatic.hbm.xml</value>
          <value>com/clr/backend/businessobject/FeedFiles.hbm.xml</value>
          </list>
          </property>
          <property name="hibernateProperties">
          <props>
          <prop key="hibernate.dialect">net.sf.hibernate.dialect.O racle9Dialect</prop>
          <prop key="hibernate.show_sql">true</prop>
          <prop key="hibernate.cglib.use_reflection_optimizer">tru e</prop>
          <prop key="hibernate.cache.provider_class">net.sf.hibern ate.cache.HashtableCacheProvider</prop>
          </props>
          </property>
          <property name="dataSource">
          <ref local="dataSource"/>
          </property>
          </bean>
          <!-- Spring Data Access Exception Translator Defintion -->
          <bean id="jdbcExceptionTranslator" class="org.springframework.jdbc.support.SQLErrorCo deSQLExceptionTranslator">
          <property name="dataSource">
          <ref bean="dataSource"/>
          </property >
          </bean>
          <!-- Hibernate Template Defintion -->
          < bean id="hibernateTemplate" class="org.springframework.orm.hibernate.Hibernate Template">
          <property name="sessionFactory">
          <ref bean="sessionFactory"/>
          </property>
          <property name="jdbcExceptionTranslator">
          <ref bean="jdbcExceptionTranslator"/>
          </property>
          </bean>
          <!-- FeedManager DAO Definition: Hibernate implementation -->
          <bean id="feedManagerDao" class="com.clr.backend.dao.hibernate.FeedManagerDa oHibernateImpl">
          <property name="hibernateTemplate">
          <ref bean="hibernateTemplate"/>
          </property>
          </bean>
          <!-- User DAO object: Hibernate implementation -->
          <bean id="userDao" class="com.clr.backend.dao.hibernate.UserDaoHibern ateImpl">
          <property name="hibernateTemplate">
          <ref bean="hibernateTemplate"/>
          </property>
          </bean>
          <!-- ========================= Start of SERVICE DEFINITIONS ========================= -->
          <!-- Hibernate Transaction Manager Definition -->
          <bean id="transactionManager" class="org.springframework.orm.hibernate.Hibernate TransactionManager">
          <property name="sessionFactory">
          <ref local="sessionFactory"/>
          </property>
          </bean>

          <!-- User Service Defintion -->
          <!-- FeedManager Service Definition -->
          <bean id="feedManagerServiceTarget" class="com.clr.backend.service.impl.FeedManagerSer viceImpl">
          <property name="feedManagerDao">
          <ref local="feedManagerDao"/>
          </property>
          </bean>
          <!-- Transactional proxy for the Catalog Service -->
          <bean id="feedManagerService" class="org.springframework.transaction.interceptor .TransactionProxyFactoryBean">
          <property name="transactionManager">
          <ref local="transactionManager"/>
          </property>
          <property name="target">
          <ref local="feedManagerServiceTarget"/>
          </property>
          <property name="transactionAttributes">
          <props>
          <prop key="get*">PROPAGATION_REQUIRED</prop>
          </props>
          </property>
          </bean>
          </beans>




          I configured the database to have a dbpool and then tried without this server pool, it doesn't work anyway. This is the error i get:

          (ungültige argument in anruf means Wrong call parameters. When i tried the same parameters without the UserCredentials just with a BasicDataSource specifying username and pwd it works. The error comes when i introduce the targetDataSource bean)



          11:21:35,176 INFO Configuration:661 - processing foreign key constraints
          11:21:35,223 INFO Dialect:82 - Using dialect: net.sf.hibernate.dialect.Oracle9Dialect
          11:21:35,238 INFO SettingsFactory:63 - Use outer join fetching: true
          11:21:35,238 INFO ConnectionProviderFactory:53 - Initializing connection provider: org.springframework.orm.hibernate.LocalDataSourceC onnectionProvider
          11:21:35,254 INFO TransactionManagerLookupFactory:33 - No TransactionManagerLookup configured (in JTA environment, use of process level read-write cache is not recomme
          11:21:35,520 WARN JDBCExceptionReporter:38 - SQL Error: 0, SQLState: null
          11:22:51,522 ERROR JDBCExceptionReporter:46 - Cannot create PoolableConnectionFactory
          11:22:51,522 WARN SettingsFactory:96 - Could not obtain connection metadata
          org.apache.commons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory, cause:
          java.sql.SQLException: Ung³ltige Argumente in Aufruf
          at oracle.jdbc.dbaccess.DBError.throwSqlException(DBE rror.java:134)
          at oracle.jdbc.dbaccess.DBError.throwSqlException(DBE rror.java:179)
          at oracle.jdbc.dbaccess.DBError.check_error(DBError.j ava:1160)
          at oracle.jdbc.ttc7.TTC7Protocol.logon(TTC7Protocol.j ava:184)
          at oracle.jdbc.driver.OracleConnection.<init>(OracleC onnection.java:362)
          at oracle.jdbc.driver.OracleDriver.getConnectionInsta nce(OracleDriver.java:536)
          at oracle.jdbc.driver.OracleDriver.connect(OracleDriv er.java:328)
          at org.apache.commons.dbcp.DriverConnectionFactory.cr eateConnection(DriverConnectionFactory.java:82)
          at org.apache.commons.dbcp.PoolableConnectionFactory. makeObject(PoolableConnectionFactory.java:300)
          at org.apache.commons.dbcp.BasicDataSource.validateCo nnectionFactory(BasicDataSource.java:838)
          at org.apache.commons.dbcp.BasicDataSource.createData Source(BasicDataSource.java:821)
          at org.apache.commons.dbcp.BasicDataSource.getConnect ion(BasicDataSource.java:532)
          at org.springframework.jdbc.datasource.UserCredential sDataSourceAdapter.doGetConnection(UserCredentials DataSourceAdapter.java:137)
          at org.springframework.jdbc.datasource.UserCredential sDataSourceAdapter.getConnection(UserCredentialsDa taSourceAdapter.java:120)
          at org.springframework.orm.hibernate.LocalDataSourceC onnectionProvider.getConnection(LocalDataSourceCon nectionProvider.java:59)
          at net.sf.hibernate.cfg.SettingsFactory.buildSettings (SettingsFactory.java:73)
          at net.sf.hibernate.cfg.Configuration.buildSettings(C onfiguration.java:1155)
          at net.sf.hibernate.cfg.Configuration.buildSessionFac tory(Configuration.java:789)
          at org.springframework.orm.hibernate.LocalSessionFact oryBean.newSessionFactory(LocalSessionFactoryBean. java:475)
          at org.springframework.orm.hibernate.LocalSessionFact oryBean.afterPropertiesSet(LocalSessionFactoryBean .java:413)
          at org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.invokeInitMethods(Abstr actAutowireCapableBeanFactory.java:990)
          at org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.createBean(AbstractAuto wireCapableBeanFactory.java:275)
          at org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.createBean(AbstractAuto wireCapableBeanFactory.java:193)
          at org.springframework.beans.factory.support.Abstract BeanFactory.getBean(AbstractBeanFactory.java:240)
          at org.springframework.beans.factory.support.Abstract BeanFactory.getBean(AbstractBeanFactory.java:163)
          at org.springframework.beans.factory.support.DefaultL istableBeanFactory.preInstantiateSingletons(Defaul tListableBeanFactory.java:230)
          at org.springframework.context.support.AbstractApplic ationContext.refresh(AbstractApplicationContext.ja va:304)
          at org.springframework.web.context.support.XmlWebAppl icationContext.refresh(XmlWebApplicationContext.ja va:131)
          at org.springframework.web.context.ContextLoader.crea teWebApplicationContext(ContextLoader.java:167)
          at org.springframework.web.context.ContextLoader.init WebApplicationContext(ContextLoader.java:101)
          at org.springframework.web.context.ContextLoaderServl et.init(ContextLoaderServlet.java:80)
          at javax.servlet.GenericServlet.init(GenericServlet.j ava:258)
          at weblogic.servlet.internal.ServletStubImpl$ServletI nitAction.run(ServletStubImpl.java:993)
          at weblogic.security.acl.internal.AuthenticatedSubjec t.doAs(AuthenticatedSubject.java:317)
          at weblogic.security.service.SecurityManager.runAs(Se curityManager.java:118)
          at weblogic.servlet.internal.ServletStubImpl.createSe rvlet(ServletStubImpl.java:869)
          at weblogic.servlet.internal.ServletStubImpl.createIn stances(ServletStubImpl.java:848)
          at weblogic.servlet.internal.ServletStubImpl.prepareS ervlet(ServletStubImpl.java:787)
          at weblogic.servlet.internal.WebAppServletContext.pre loadServlet(WebAppServletContext.java:3252)
          at weblogic.servlet.internal.WebAppServletContext.pre loadServlets(WebAppServletContext.java:3209)
          at weblogic.servlet.internal.WebAppServletContext.pre loadServlets(WebAppServletContext.java:3195)
          at weblogic.servlet.internal.WebAppServletContext.pre loadResources(WebAppServletContext.java:3174)
          at weblogic.servlet.internal.WebAppServletContext.set Started(WebAppServletContext.java:5647)
          at weblogic.servlet.internal.WebAppModule.start(WebAp pModule.java:869)
          at weblogic.j2ee.J2EEApplicationContainer.start(J2EEA pplicationContainer.java:2022)
          at weblogic.j2ee.J2EEApplicationContainer.activate(J2 EEApplicationContainer.java:2063)
          at weblogic.management.deploy.slave.SlaveDeployer$Com ponentActivateTask.activateContainer(SlaveDeployer .java:2592)
          at weblogic.management.deploy.slave.SlaveDeployer$Act ivateTask.doCommit(SlaveDeployer.java:2515)
          at weblogic.management.deploy.slave.SlaveDeployer$Tas k.commit(SlaveDeployer.java:2317)
          at weblogic.management.deploy.slave.SlaveDeployer$Tas k.checkAutoCommit(SlaveDeployer.java:2399)
          at weblogic.management.deploy.slave.SlaveDeployer$Tas k.prepare(SlaveDeployer.java:2311)
          at weblogic.management.deploy.slave.SlaveDeployer$Act ivateTask.prepare(SlaveDeployer.java:2479)
          at weblogic.management.deploy.slave.SlaveDeployer.pro cessPrepareTask(SlaveDeployer.java:798)
          at weblogic.management.deploy.slave.SlaveDeployer.pre pareDelta(SlaveDeployer.java:507)
          at weblogic.management.deploy.slave.SlaveDeployer.pre pareUpdate(SlaveDeployer.java:465)
          at weblogic.drs.internal.SlaveCallbackHandler$1.execu te(SlaveCallbackHandler.java:25)
          at weblogic.kernel.ExecuteThread.execute(ExecuteThrea d.java:197)
          at weblogic.kernel.ExecuteThread.run(ExecuteThread.ja va:170)
          11:22:51,553 INFO SettingsFactory:103 - Use scrollable result sets: false
          11:22:51,553 INFO SettingsFactory:106 - Use JDBC3 getGeneratedKeys(): false
          11:22:51,553 INFO SettingsFactory:109 - Optimize cache for minimal puts: false
          11:22:51,553 INFO SettingsFactory:115 - echoing all SQL to stdout
          11:22:51,553 INFO SettingsFactory:118 - Query language substitutions: {}

          Any indea?

          Thanks a lot for your help

          Comment


          • #6
            how to do? I also want to know.

            how to do? I also want to know.

            Comment

            Working...
            X