有没有办法从Hibernate使用Postgresql副本(在表中加载CSV)?

时间:2016-01-28 09:19:00

标签: java hibernate postgresql csv postgresql-copy

在我目前的应用程序中,我正在使用Hibernate + PostgreSQL。对于特定情况,我需要使用postgres中可用的COPY功能从CSV文件加载数据。有没有办法使用Hibernate COPY

Postgres version : 9.4
Hibernate version : 5.0.6

1 个答案:

答案 0 :(得分:3)

基于@ a-horse-with-name-comment,我将以下代码放在一起,因为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 );

希望这有助于读者。