【问题标题】:List all DB tables - JPA列出所有数据库表 - JPA
【发布时间】:2019-05-04 16:12:06
【问题描述】:

我想使用 Spring boot 和 JPA 列出我的数据库中的所有表,我创建了一个 DataSource 配置,例如 - configuring-spring-boot-for-oracle 并尝试了 -

@Repository
public interface  TestRepo extends JpaRepository<Table, Long>{
    @Query("SELECT owner, table_name  FROM dba_tables")
    List<Table> findAllDB();
}

还有我的 Table 实体 -

@Entity
public class Table {
    String owner;
    String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getOwner() {
        return owner;
    }

    public void setOwner(String owner) {
        this.owner = owner;
    }

}

得到了——

No identifier specified for entity: com.siemens.plm.it.aws.connect.repos.Table

那么如何查询数据库表名呢? 到目前为止我的主要 -

@SpringBootApplication
public class AwsFileUploadApplication implements CommandLineRunner{

    @Autowired
    DataSource dataSource;
    @Autowired
    TestRepo repo;

    public static void main(String[] args) {
        //https://wwwtest.plm.automation.siemens.com/subsadmin/app/products
        SpringApplication.run(AwsFileUploadApplication.class, args);

    }

    @Override
    public void run(String... args) throws Exception {
        System.out.println("DATASOURCE = " + dataSource); //some value - ds init sucess
        List<Table> findAllDB = repo.findAllDB();
        System.out.println(findAllDB);
        }
    }

从表中删除 @Entity 时 - Not a managed type: class com.siemens.plm.it.aws.connect.repos.Table

【问题讨论】:

  • 你不应该有一个实体:一个实体应该有一个 ID,并被映射到一个数据库表。相反,您应该使用返回元组的本机 SQL 查询。您当前正在定义 JPQL 查询,而 JPQL 不使用表和列,而是使用实体及其属性。
  • 任何实体都必须具有@Id 属性。假设名称是唯一的,然后将其粘贴在上面。
  • @JBNizet - 尝试原生版本,谢谢。

标签: oracle spring-boot jpa


【解决方案1】:

我使用 JDBC 打印所有表和列:

    @Autowired
    protected DataSource dataSource;

    public void showTables() throws Exception {
        DatabaseMetaData metaData = dataSource.getConnection().getMetaData();
        ResultSet tables = metaData.getTables(null, null, null, new String[] { "TABLE" });
        while (tables.next()) {
            String tableName=tables.getString("TABLE_NAME");
            System.out.println(tableName);
            ResultSet columns = metaData.getColumns(null,  null,  tableName, "%");
            while (columns.next()) {
                String columnName=columns.getString("COLUMN_NAME");
                System.out.println("\t" + columnName);
            }
        }
    }

如果您查看getTables API,您可以了解如何优化表格搜索。

【讨论】:

  • 如何只获取一个数据库或数据库模式的表?它甚至打印 MySQL 的 sys_config
猜你喜欢
  • 2016-01-15
  • 1970-01-01
  • 1970-01-01
  • 2010-10-24
  • 2011-06-09
  • 1970-01-01
  • 1970-01-01
  • 2022-12-31
相关资源
最近更新 更多