簡體   English   中英

如何向Postgresql CopyManager指示會話實例

[英]How to indicate a session instance to Postgresql CopyManager

我有一個使用休眠模式來管理數據庫操作的Java Web項目。

有兩個按順序執行的SQL:

  1. 執行“ CREATE TEMP temp_table ...;” 通過休眠本機sql查詢。
  2. 通過org.postgresql.copy.CopyManager執行“從SDTIN復制TEMP_table”,以將CSV文件傳輸到temp_table。

我的代碼:

public boolean loadElectricFishData(Integer fileId, File eventfile, File samplefile) {
    Session session = stagingSessionFactory.getCurrentSession();
    String elecCountTableName = "temp_eb_elec_count_" + fileId;

    return createTable(session, elecCountTableName , "nemostaging.eb_elec_count")
            && copyTableFromCSV(session, elecCountTableName, eventfile) ? true : false;
}

private boolean createTable(Session session, String tableName, String likeTableName) {
    SQLQuery query = session.createSQLQuery("CREATE TABLE nemostaging." + tableName + " (LIKE " + likeTableName + " INCLUDING ALL)");
    query.executeUpdate();
    session.flush();
    session.close();
    return true;
}

private boolean copyTableFromCSV(Session session, final String tableName, final File csv) {
    SessionImpl sessionImpl = (SessionImpl)session;
    Connection connection = sessionImpl.getTransactionCoordinator().getJdbcCoordinator().getLogicalConnection().getConnection();
    FileReader fileReader = null;
    try {
        CopyManager copyManager = new CopyManager((BaseConnection) connection);
        fileReader = new FileReader(csv);
        copyManager.copyIn("COPY nemostaging." + tableName + " FROM STDIN DELIMITER ',' CSV HEADER", fileReader);
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        if (fileReader != null) {
            try {
                fileReader.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    return false;
}

我的問題是這兩個操作需要相同的會話,因為臨時表對另一個會話不可見。 而CopyManager不會重用同一會話。 任何人都有一個主意,該如何指示org.postgresql.copy.CopyManager的當前會話,而不只是當前的連接?

非常感謝!

------ Update-2015-11-13 -----嗨,克雷格·林格,我嘗試了您的建議,但有一個例外:

com.sun.proxy。$ Proxy20.unwrap中的java.lang.reflect.UndeclaredThrowableException(nz.co.niwa.nemo.uploadservice.core.dao.impl.StagingLoadDataDaoImpl $ 1.execute(StagingLoadDataDaoImpl.java:88)在org.hibernate.jdbc.WorkExecutor.executeWork(WorkExecutor.java:54)在org.hibernate.internal.SessionImpl $ 2.accept(SessionImpl.java:1933)在org.hibernate.internal.SessionImpl $ 2.accept(SessionImpl.java) :1930),位於org.hibernate.internal.SessionImpl.doWork(SessionImpl.java:1951)的org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.coordinateWork(JdbcCoordinatorImpl.java:211),位於org.hibernate.internal.SessionImpl。 doWork(SessionImpl.java:1937)位於nz.co.niwa.nemo.uploadservice.core.dao.impl.StagingLoadDataDaoImpl.loadSpotlightData(StagingLoadDataDaoImpl.java:85)位於sun.reflect.NativeMethodAccessorImpl.invoke0(本地方法)。在sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.invoke.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) 的org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:319)的java.lang.reflect.Method.invoke(Method.java:597)的java.25) org.org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)上的org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)上的.invokeJoinpoint(ReflectiveMethodInvocation.java:183)。 org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)上的springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation。 java:172)在org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:90)在org.springframework.aop.framework.ReflectiveMethodInvocation.procee d(ReflectiveMethodInvocation.java:172)在org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)在com.sun.proxy。$ Proxy14.loadSpotlightData(未知源)在nz.co.niwa.nemo nz.co.niwa.nemo.uploadservice.core.service.impl.StagingLoadDataServiceImpl.loadSpotlightData(StagingLoadDataServiceImpl.java:44)上的.uploadservice.core.manage.impl.StagingLoadDataManageImpl.loadSpotlightData(StagingLoadDataManageImpl.java:30)在nz.co. .niwa.nemo.uploadservice.core.test.service.StagingLoadDataServiceTest.testLoadSpotlightData(StagingLoadDataServiceTest.java:39)位於sun.reflect.NativeMethodAccessorImpl.invoke0(本地方法),位於sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)在org.junit.runners.model.FrameworkMethod $ 1.runReflectiveCall(FrameworkMethod.java :)在java.lang.reflect.Method.invoke(Method.java:597)在sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) 45)在org.junit.internal.runners.model.Ref org.junit.runners.model.FrameworkMethod.invoke上的lectiveCallable.run(ReflectiveCallable.java:15)org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)上的Explosively(FrameworkMethod.java:42)在org.springframework.org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)在org.springframework.org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)在org.springframework org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)上的.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)在org.junit.runners.BlockJUnit4ClassRunner.runChild上(BlockJUnit4ClassRunner.java:47)在org.junit.runners.ParentRunner $ 3.run(ParentRunner.java:231)在org.junit.runners.ParentRunner $ 1.schedule(ParentRunner.java:60)在org.junit.runners。 org.junit.runners.ParentRunn上的ParentRunner.runChildren(ParentRunner.java:229) 在org.junit.runners.er.access $ 000(ParentRunner.java:50)在org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:$2.evaluate(ParentRunner.java:222) 61)在org.springit.runners.ParentRunner.run(ParentRunner.java:300)在org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)在org.springframework.test.context org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)的.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)在org.eclipse.jdt.internal.junit.runner.TestExecutionion org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)上的.run(TestExecution.java:38)在org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner。 .java:675),位於org.eclipse.jdt.int的org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) ernal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)由以下原因引起:java.lang.reflect.InvocationTargetException在sun.reflect.NativeMethodAccessorImpl.invoke0(本機方法)處在sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java :39),位於org.hibernate.engine.jdbc.internal.proxy.ConnectionProxyHandler的java.lang.reflect.Method.invoke(Method.java:597)的sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)處。 org.hibernate.engine.jdbc.internal.proxy.AbstractProxyHandler.invoke(AbstractProxyHandler.java:81)處的continueInvocation(ConnectionProxyHandler.java:130)... 55更多原因:java.sql.SQLException:無法解包到org。 org.postgresql.jdbc4.AbstractJdbc4Connection.unwrap(AbstractJdbc4Connection.java:269)的postgresql.copy.CopyManager ... 61更多

我的代碼:

public boolean loadSpotlightData(final Integer fileId, final File datafile) {
    final String spotCountTableName = "tmp_eb_spot_count_" + fileId;
    Session session = stagingSessionFactory.getCurrentSession();
    SQLQuery query = session.createSQLQuery("CREATE TEMP TABLE " + spotCountTableName + " (LIKE nemostaging.eb_spot_count INCLUDING ALL)");
    query.executeUpdate();
    session.doWork(new Work() {
        @Override
        public void execute(Connection connection) throws SQLException {
            CopyManager copyManager = connection.unwrap(org.postgresql.copy.CopyManager.class);
            FileReader fileReader = null;
            try {
                fileReader = new FileReader(datafile);
                copyManager.copyIn("COPY " + spotCountTableName + " FROM STDIN DELIMITER ',' CSV HEADER", fileReader);
            } catch (SQLException e) {
                LOG.error("Errors occur while COPY nemostaging." + spotCountTableName + " FROM STDIN DELIMITER ',' CSV HEADER;", e);
            } catch (FileNotFoundException e) {
                LOG.error("The CSV file cannot be found while copying into database.", e);
            } catch (IOException e) {
                LOG.error("Errors occur while reading the csv file.", e);
            } finally {
                if (fileReader != null) {
                    try {
                        fileReader.close();
                    } catch (IOException e) {
                        LOG.error("Errors occur while closing file reader.", e);
                    }
                }
            }
        }
    });

    Query query1 = session.getNamedQuery("staging.loadSpotlightData");
    query1.setParameter("fileId", fileId);
    query1.list();

    return true;
}

您必須做的是運行Hibernate查詢,然后要求Hibernate Session獲取實現org.postgresql.PGConnection的基礎Connection對象並使用它。

您曾經能夠使用Session.connection()方法解開會話,但是現在不建議使用。 而是使用doWork API 您傳遞的java.sql.Connection也可能由連接池包裝,因此您可能必須將其拆包以獲取實際的連接對象。 如果正在使用JDBC4驅動程序和池(應該使用),則只需使用Connection實現的Wrapper接口中unwrap(...)方法即可 ,例如unwrap(org.postgresql.copy.CopyManager.class)

像(未經測試的):

session.doWork(
    new Work() {
        public void execute(Connection connection) throws SQLException 
        { 
            CopyManager cm = connection.unwrap(org.postgresql.copy.CopyManager.class);
            ... do stuff ...
        }
    }
);

您不能直接從DriverManager創建新的單獨連接,也不能將其與另一個會話的臨時表一起使用。 您也不需要。 最好從Hibernate會話中取消池化連接。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM