将数据从数据表提取到 JPA 中的文本文件



我正在研究数据操作,我的命令是将表的所有内容提取到文本文件中!我已经实现了这个,但是学徒,我在创建请求时犯了一个错误:

public void extractDonneesFichierPlat(){
TypedQuery<NotificationCnavOP> query = entityManager.createQuery("SELECT * INTO OUTFILE 'C:\Test.txt' FROM NotificationCnavOP", NotificationCnavOP.class);
}

不能使用"select * into outfile..."JPQL 中的语法,这是一种不同于 SQL 的独立查询语言。如果要在 JPA 中执行本机 SQL 查询,则必须使用entityManager.createNativeQuery()方法。 但是仍然无法使用此方法执行此类"批量操作"查询。 我能想到的唯一解决方案是使用 JDBC 而不是 JPA 并执行:

Object o = entityManager.getDelegate();
System.out.println(o.getClass()); //prints the object class
// in my case it is org.hibernate.internal.SessionImpl
SessionImpl s = (SessionImpl)o;
Connection c = s.connection();
try {    
Statement stmt = c.createStatement();
stmt.executeQuery("SELECT * INTO OUTFILE 'C:/Test.txt' FROM NotificationCnavOP");
} catch (SQLException e) {
e.printStackTrace();
}

Session的实际实现取决于提供程序。在休眠的情况下,它是org.hibernate.internal.SessionImpl.

对于较新版本的Hibernate,它是org.hibernate.Session的,并且没有connection()方法。 因此,您应该尝试:

Object o = entityManager.getDelegate();
Session s = (Session)o;
s.doWork(connection -> {
try {    
Statement stmt = connection.createStatement();
stmt.executeQuery("SELECT * INTO OUTFILE 'C:/Test2.txt' FROM NotificationCnavOP");
} catch (SQLException e) {
e.printStackTrace();
}
}); 

这两个版本都可以在Hibernate 4中使用。

最新更新