有时,在使用 DDL 时
生成运行脚本很有用
首先清理数据库。在
如果您放置一个名为的文件,则休眠
类路径上的“import.sql”
内容将被发送到数据库。
就个人而言,我不是魔术迷
文件名,但这可能很有用
功能。
没有对此的内置支持
在 EclipseLink 中,但很容易做到
感谢 EclipseLink 的高
可扩展性。这是一个快速的解决方案
我想出了:我只需注册一个
会话的事件监听器
postLogin 事件和在处理程序中我
读取文件并发送每个 SQL
对数据库的声明——很好
干净的。我走得更远了
支持设置文件名
作为持久性单元属性。你
可以在代码中或在
持久性.xml。
ImportSQL 类配置为
一个SessionCustomizer 通过一个
持久性单元属性,其中
postLogin 事件,读取文件
由“import.sql.file”标识
财产。这个楼盘也是
指定为持久性单元
传递给的属性
createEntityManagerFactory。这
示例还显示了如何定义
并使用您自己的持久性单元
属性。
import org.eclipse.persistence.config.SessionCustomizer;
import org.eclipse.persistence.sessions.Session;
import org.eclipse.persistence.sessions.SessionEvent;
import org.eclipse.persistence.sessions.SessionEventAdapter;
import org.eclipse.persistence.sessions.UnitOfWork;
public class ImportSQL implements SessionCustomizer {
private void importSql(UnitOfWork unitOfWork, String fileName) {
// Open file
// Execute each line, e.g.,
// unitOfWork.executeNonSelectingSQL("select 1 from dual");
}
@Override
public void customize(Session session) throws Exception {
session.getEventManager().addListener(new SessionEventAdapter() {
@Override
public void postLogin(SessionEvent event) {
String fileName = (String) event.getSession().getProperty("import.sql.file");
UnitOfWork unitOfWork = event.getSession().acquireUnitOfWork();
importSql(unitOfWork, fileName);
unitOfWork.commit()
}
});
}
public static void main(String[] args) {
Map<String, Object> properties = new HashMap<String, Object>();
// Enable DDL Generation
properties.put(PersistenceUnitProperties.DDL_GENERATION, PersistenceUnitProperties.DROP_AND_CREATE);
properties.put(PersistenceUnitProperties.DDL_GENERATION_MODE, PersistenceUnitProperties.DDL_DATABASE_GENERATION);
// Configure Session Customizer which will pipe sql file to db before DDL Generation runs
properties.put(PersistenceUnitProperties.SESSION_CUSTOMIZER, "model.ImportSQL");
properties.put("import.sql.file","/tmp/someddl.sql");
EntityManagerFactory emf = Persistence
.createEntityManagerFactory("employee", properties);
}