java - Hibernate将sql保存到文件

标签 java sql hibernate file

我想将实体序列化为 SQL 查询字符串并将其保存到 .txt 文件中,以便稍后能够将其写入数据库。我需要该解决方案无论使用哪种 SQL 方言都能工作,因此我想使用 Hibernate。

可以用 Hibernate 来实现吗?您能给我一个线索或教程吗?我怎样才能做到这一点?

假设我们有一个实体:

@Entity  
public class Project {
       @Id
       @GeneratedValue(strategy = GenerationType.SEQUENCE)
       private Long id;
       private String name;

       //... setters, getters and constructor
}

我想将一些实体序列化为 SQL 语句字符串,如下所示:

INSERT INTO project (name)
VALUES ('SQL Convertion Project');
INSERT INTO project (name)
VALUES ('DB Migration');
INSERT INTO project (name)
VALUES ('Stackoverflow is cool');

最佳答案

我找到了解决方案。我希望它会对某人有所帮助。

下面的代码使用 Hibernate 实体持久器获取实体项目的插入和更新查询。如果需要,我可以注入(inject)查询参数并将查询写入文件。

  1. 仅使用 Hibernate 框架:
Configuration configuration = new Configuration().configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().
        applySettings(configuration.getProperties());
SessionFactory sessionFactory = configuration.buildSessionFactory(builder.build());
ClassMetadata hibernateMetadata = sessionFactory.getClassMetadata("com.mypackage.Project ");
if (hibernateMetadata == null){
    return;
}

if (hibernateMetadata instanceof AbstractEntityPersister) {
    AbstractEntityPersister persister = (AbstractEntityPersister) hibernateMetadata;

    for (Method method : persister.getClass().getSuperclass().getDeclaredMethods()) {
        if (method.getName().equalsIgnoreCase("getSQLInsertStrings")) {
            ReflectionUtils.makeAccessible(method);
            Object insertQueries = ReflectionUtils.invokeMethod(method, persister);

            for (String queryText : (String []) insertQueries) {
                System.out.println(queryText);
            }
        }

        if (method.getName().equalsIgnoreCase("getSQLUpdateStrings")) {
            ReflectionUtils.makeAccessible(method);
            Object insertQueries = ReflectionUtils.invokeMethod(method, persister);

            for (String queryText : (String []) insertQueries) {
                System.out.println(queryText);
            }
        }
    }
}
  • 使用 Hibernate + Spring
  • ApplicationContext ctx = new ClassPathXmlApplicationContext( "ApplicationContext.xml");

    EntityManager em = ((EntityManagerFactory) ctx.getBean("entityManagerFactory")).createEntityManager();
    try {
        Session session = em.unwrap(Session.class);
    
        ClassMetadata hibernateMetadata = session.getSessionFactory().getClassMetadata("com.mypackage.Project");
        if (hibernateMetadata == null){
            return;
        }
        if (hibernateMetadata instanceof AbstractEntityPersister) {
            AbstractEntityPersister persister = (AbstractEntityPersister) hibernateMetadata;
    
            for (Method method : persister.getClass().getSuperclass().getDeclaredMethods()) {
                if (method.getName().equalsIgnoreCase("getSQLInsertStrings")) {
                    ReflectionUtils.makeAccessible(method);
                    Object insertQueries = ReflectionUtils.invokeMethod(method, persister);
    
                    for (String queryText : (String []) insertQueries) {
                        System.out.println(queryText);
                    }
                }
    
                if (method.getName().equalsIgnoreCase("getSQLUpdateStrings")) {
                    ReflectionUtils.makeAccessible(method);
                    Object insertQueries = ReflectionUtils.invokeMethod(method, persister);
    
                    for (String queryText : (String []) insertQueries) {
                        System.out.println(queryText);
                    }
                }
            }
    
        }
    }
    finally {
        if (em != null) {
            em.close();
        }
    }
    

    关于java - Hibernate将sql保存到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26797837/

    相关文章:

    java - 客户端-服务器套接字编程

    java - Ant 将文件复制到叶目录

    MySQL - 将 ID 匹配到 Max of Count ("Need"更优雅的解决方案)

    java - spring data hibernate 延迟加载

    java - 对象和引用创建

    java - 创建自定义 RecyclerView 项目分隔符时出现空类

    mysql - sql如何用新的唯一值替换数千个唯一值

    sql - SQLite 是否足够强大以用作 wordpress 数据库?

    hibernate - 如果@EmbeddedId的Any字段值为null,会出现什么问题?

    java - 无法反序列化 - Hibernate Spring Boot