title: Saving a file in postgres database using native query
body: <p>I am trying to save a file in the database. I am able to save using SQL it works perfectly fine. What I am avoiding with SQL is providing password directly in the code that why I am considering using native query. I am unsure if I can still use SQL without providing password and username directly in the code.The code for the SQL is as below</p>
  
  <pre><code> try {
          Class.forName("org.postgresql.Driver");
      } catch (ClassNotFoundException e) {
          e.printStackTrace();
      }
      Connection connection = null;
  
      try {
          connection = DriverManager.getConnection(
                  "jdbc:postgresql://localhost:5432/mydb", "postgres",
                  "postgres");
  
          System.out.println("......Now attempting to insert the record.....");
         // String matid = "007N00030000001";
  
          File file = new File("C://JavaWorkspace/pdf-sample.pdf");
          FileInputStream fis = new FileInputStream(file);
  
          PreparedStatement ps = connection.prepareStatement("INSERT INTO cli.documents VALUES (?,?,?,?)");
          ps.setBinaryStream(1, fis, (int)file.length());
          ps.setString(2, "1");
          ps.setString(3, file.getName());
          ps.setString(4,matid);
          ps.executeUpdate();
          ps.close();
          fis.close();
  
      } catch (SQLException e) {
          e.printStackTrace();
      } catch (FileNotFoundException e) {
          e.printStackTrace();
      } catch (IOException e) {
          e.printStackTrace();
      }
  </code></pre>
  
  <p>If using native query I cant see any method that I can use instead of 
  <strong>ps.setBinaryStream(1, fis, (int)file.length());</strong>
  there is only setParameter 
  below is my attempt using native query</p>
  
  <pre><code>          Query query = entityManager.createNativeQuery("INSERT INTO cli.documents (matid, doctype,upload,docfile) " +
                 " VALUES(?,?,?,?)");
         EntityManagerFactory emfactory=Persistence.createEntityManagerFactory( "junit" );
         EntityManager em = emfactory.createEntityManager( ); //= null;
         EntityTransaction et = em.getTransaction();
         et.begin();
          em.createNativeQuery("INSERT INTO cli.documents (matid, doctype,upload,docfile) " +  " VALUES(?,?,?,?)")
          .setParameter(1,matid)
          .setParameter(2, "1")
          .setParameter(3, file.getName())
          .setParameter(4, (int)file.length());
          //.setBinaryStream(4, fis, (int)file.length())
          // em.executeUpdate()
          et.commit();
  </code></pre>