3

In my current application I am using Hibernate + PostgreSQL. For a particular case I need to use the COPY functionality available in postgres to load data from CSV file. Is there any way to use COPY using Hibernate.

Postgres version : 9.4
Hibernate version : 5.0.6
Vivek S.
  • 19,945
  • 7
  • 68
  • 85
Ketu
  • 1,608
  • 2
  • 14
  • 30
  • What have you attempted so far? – Blaze Jan 28 '16 at 09:28
  • I'm new to Hibernate, so couldn't do much with Hibernate. I am able to do this using jdbc type 4 connection. If you are interested in that I can share that code, however it will be irrelevant to the topic – Ketu Jan 28 '16 at 09:32
  • 2
    Hibernate will not support that. But you _can_ use `copy from stdin` from JDBC using the [`CopyManager` API](https://jdbc.postgresql.org/documentation/publicapi/org/postgresql/copy/CopyManager.html). See e.g. here: http://stackoverflow.com/questions/33648947/how-to-indicate-a-session-instance-to-postgresql-copymanager –  Jan 28 '16 at 09:54
  • @a_horse_with_no_name thanks for the reference link, gave me a way forward. – Ketu Jan 29 '16 at 06:57

1 Answers1

6

Based on @a-horse-with-no-name comment, I put together following code as session.doWork is deprecated.

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 );

Hope this helps readers.

Ketu
  • 1,608
  • 2
  • 14
  • 30