Hibernate - 使用文件写入将数据导出到csv文件中

时间:2014-11-27 11:05:22

标签: java hibernate file csv

我正在尝试将数据从hibernate(使用HQL中的select语句)导出到文本文件。我使用简单的文件写入机制将输出写入文本文件。在将数据写入文本文件时,会插入垃圾值,但在SYSO中,值会正确显示。 这可能是一个小小的错误,但我长期坚持这一点。

任何帮助都将不胜感激。

我也附上了代码

public class Logic {
@SuppressWarnings({ "rawtypes", "deprecation" })
public static void main(String[] args) throws IOException {

    Configuration cfg = new Configuration();
    cfg.configure("hibernate.cfg.xml");

    SessionFactory factory = cfg.buildSessionFactory();
    Session session = factory.openSession();

   File file = new File("D:/Users/output.txt"); 

    FileWriter fw = new FileWriter(file);
    BufferedWriter bw = new BufferedWriter(fw);


    Query qry = session.createQuery("SELECT A from Employee_details A");
    List l =(List) qry.list();
    System.out.println("Total Number Of Records : "+((java.util.List) l).size());
    Iterator it = ((java.util.List) l).iterator();

    while(it.hasNext())
    {
        Object o = (Object)it.next();
        Employee_details e = (Employee_details)o;
        System.out.println("Employee ID : "+e.getId());
        System.out.println("Employee Name : "+e.getName());
        System.out.println("Employee Salary : "+ e.getSalary());
        System.out.println("----------------------");
        bw.write(e.getId()); // Here instead of Id some junk value is getting inserted
     } 
    bw.flush();
    bw.close();

    }
}

1 个答案:

答案 0 :(得分:0)

// Other Hibernate code here
PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter("D:/Users/output.txt"))); 
System.out.println("Total Number Of Records : "+((java.util.List) l).size());
Iterator it = ((java.util.List) l).iterator();    
while(it.hasNext())
   {
        writer.println(e.getId());
   } 

writer.close(); // put this in finally block