1

I'm using PostgreSQL database,and i have a select query result.I want this query result to save in .dat file.How can i achieve this?

@Repository
public interface EmpHeaderRepository extends JpaRepository<EmpHeaderDetails, Long> {

    @Query("select e.header_info from EmpHeaderDetails e" )
    public List<EmpHeaderDetails> findByHeader_info(String header_info);

}

This is the query in my repository.

Query result should be saved in the .dat file.How should i do this?

nortontgueno
  • 2,553
  • 1
  • 24
  • 36
Krithika
  • 23
  • 4
  • 1
    You can query all your results and just drop them into a regular file name `something.dat`, to write in a file please check [this](https://stackoverflow.com/questions/2885173/how-do-i-create-a-file-and-write-to-it-in-java) – nortontgueno Jan 30 '19 at 12:18
  • 1
    Possible duplicate of [How do I create a file and write to it in Java?](https://stackoverflow.com/questions/2885173/how-do-i-create-a-file-and-write-to-it-in-java) – nortontgueno Jan 30 '19 at 12:33
  • I'm sorry,but I'm not getting how will i insert queries to writer @ngueno – Krithika Jan 30 '19 at 13:01
  • 1
    Check Ahmet answer, you will fetch your `EmpHeaderDetails`, will iterate over them and save into a regular file. – nortontgueno Jan 30 '19 at 13:05

1 Answers1

1

You can do that by using standard File IO in Java. Just iterate through your result set and save the contents to a file. Sample code is as follows:

BufferedWriter writer = new BufferedWriter(new FileWriter("result.dat"));

for(EmpHeaderDetails ehd : ehdList) {
  writer.write(ehd.toString());
}

writer.close();
Ahmet
  • 1,045
  • 13
  • 28
  • i'm getting error with ehdList as this variable doesn't contain anything @ngueno What should i do? – Krithika Jan 30 '19 at 13:13
  • You should first use the repository `findByHeader_info` method and get the result `List` and then assign this result to `ehdList`. Then you can iterate over the collection. – Ahmet Jan 30 '19 at 13:58
  • If the answers worked for you please accept it as answer – Ahmet Jan 30 '19 at 14:27