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
4
  • What have you attempted so far? Commented Jan 28, 2016 at 9: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 Commented Jan 28, 2016 at 9:32
  • 2
    Hibernate will not support that. But you can use copy from stdin from JDBC using the CopyManager API. See e.g. here: stackoverflow.com/questions/33648947/… Commented Jan 28, 2016 at 9:54
  • @a_horse_with_no_name thanks for the reference link, gave me a way forward. Commented Jan 29, 2016 at 6:57

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.