Ketu
Ketu

Reputation: 1718

Is there a way to use Postgresql copy (loading CSV in table) from Hibernate?

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

Upvotes: 3

Views: 2482

Answers (1)

Ketu
Ketu

Reputation: 1718

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.

Upvotes: 7

Related Questions