【问题标题】:Is there a way to use Postgresql copy (loading CSV in table) from Hibernate?有没有办法从 Hibernate 使用 Postgresql 副本(在表中加载 CSV)?
【发布时间】:2016-05-05 14:01:12
【问题描述】:

在我当前的应用程序中,我使用的是 Hibernate + PostgreSQL。对于特定情况,我需要使用 postgres 中可用的 COPY 功能从 CSV 文件加载数据。有什么方法可以通过 Hibernate 使用COPY

Postgres version : 9.4
Hibernate version : 5.0.6

【问题讨论】:

  • 到目前为止你做了什么?
  • 我是 Hibernate 的新手,所以不能用 Hibernate 做太多事情。我可以使用 jdbc type 4 连接来做到这一点。如果您有兴趣我可以分享该代码,但这与主题无关
  • Hibernate 将不支持这一点。但是您可以使用来自 JDBC 的 copy from stdin 使用 CopyManager API。参见例如这里:stackoverflow.com/questions/33648947/…
  • @a_horse_with_no_name 感谢您的参考链接,给了我前进的道路。

标签: java hibernate postgresql csv postgresql-copy


【解决方案1】:

基于@a-horse-with-no-name 评论,我将以下代码放在一起,因为session.doWork 已弃用。

SessionFactory factory = HibernateUtil.getSessionFactory();
Session session = factory.openSession();
SessionImplementor sessImpl = (SessionImplementor) session;
Connection conn = null;
conn = sessImpl.getJdbcConnectionAccess().obtainConnection();
CopyManager copyManager = new CopyManager((BaseConnection) conn);
File tf =File.createTempFile("temp-file", "tmp"); 
String tempPath =tf.getParent();
File tempFile = new File(tempPath + File.separator + filename);
FileReader fileReader = new FileReader(tempFile);
copyManager.copyIn("copy testdata (col1, col2, col3) from  STDIN with csv", fileReader );

希望这对读者有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-11
    • 1970-01-01
    • 2022-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-25
    • 1970-01-01
    相关资源
    最近更新 更多