【问题标题】:Create and save an object to a table using JPA but have the table name as a parameter使用 JPA 创建对象并将其保存到表中,但将表名作为参数
【发布时间】:2014-10-16 23:02:50
【问题描述】:

所以我知道,如果我有一个正确注释的对象(比如说Message 对象),我可以这样做:

EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory(databaseName);
EntityManager entityManager = entityManagerFactory.createEntityManager();
EntityTransaction transaction = entityManager.getTransaction();
try {
      transaction.begin();

      Message msg = new Message("Message");
      entityManager.persist(msg);
      transaction.commit();
 }

并且将使用Message 注释中的任何值创建表。在这种情况下,假设Message 的对象有这个表名的注释:

@Table(name = "tableMessage")

因此,将创建表tableMessage,并将Message对象保存到表tableMessage中。

我的问题是,假设我有一个文本字段,用户将在其中输入表的名称,以保存 Message 对象(如果不存在则创建表)。

我该怎么做?如果我事先知道,我可以去Message 课程并手动更改它,但我不知道。

PS;我使用休眠作为 JPA 的实现。

【问题讨论】:

    标签: java sql hibernate jpa entity


    【解决方案1】:

    JPA 不支持动态创建和映射新表。它需要动态创建新的 Java 类并动态更新映射元数据。您可以使用 JDBC 或本机查询做任何您想做的事情。

    更多信息,请转至here

    【讨论】:

      猜你喜欢
      • 2017-10-19
      • 2011-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-23
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      相关资源
      最近更新 更多