如何在Java SpringBoot中获取PostgreSQL列名

9 浏览
0 Comments

如何在Java SpringBoot中获取PostgreSQL列名

我正在尝试获取PostgreSQL表的列名。我尝试使用information_schema,但在我的Java MVC项目中无效。我该怎么办?

这实际上是我在StackOverflow上的第一个问题,所以如果我的问题难以理解,我很抱歉。谢谢!

public interface MyFileRepository extends JpaRepository {
    @Query("select column_name,data_type from information_schema.columns where table_name = 'MyEntityModel';")
    List myList();
}

0
0 Comments

问题出现的原因:

在Java Spring Boot中使用PostgreSQL时,有时需要获取PostgreSQL数据库表的列名。然而,Spring Data JPA并没有直接提供获取列名的方法,因此开发者需要寻找其他解决方法。

解决方法:

开发者可以参考一个开放的问题,该问题在Stack Overflow上被提出:Is there any Simplest way to get Table metadata (column name list) information, in Spring Data JPA ? which could I use on universal database。该问题讨论了如何在Spring Data JPA中获取表的元数据(列名列表)信息的最简单方法,且适用于通用数据库。

为了解决这个问题,开发者可以使用如下方法来获取PostgreSQL数据库表的列名:

1. 使用JDBC元数据API:

import java.sql.*;
import org.springframework.jdbc.core.JdbcTemplate;
public class PostgresColumnNames {
    private final JdbcTemplate jdbcTemplate;
    public PostgresColumnNames(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
    public List getColumnNames(String tableName) {
        try {
            Connection connection = jdbcTemplate.getDataSource().getConnection();
            DatabaseMetaData metaData = connection.getMetaData();
            ResultSet resultSet = metaData.getColumns(null, null, tableName, null);
            
            List columnNames = new ArrayList<>();
            while (resultSet.next()) {
                String columnName = resultSet.getString("COLUMN_NAME");
                columnNames.add(columnName);
            }
            
            resultSet.close();
            connection.close();
            
            return columnNames;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        
        return Collections.emptyList();
    }
}

2. 使用Hibernate实体管理器(EntityManager):

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.metamodel.EntityType;
import java.util.List;
import java.util.stream.Collectors;
@Component
public class PostgresColumnNames {
    @PersistenceContext
    private EntityManager entityManager;
    public List getColumnNames(String tableName) {
        EntityType entityType = entityManager.getMetamodel().getEntities()
                .stream()
                .filter(e -> e.getName().equals(tableName))
                .findFirst()
                .orElseThrow(IllegalArgumentException::new);
        
        return entityType.getAttributes()
                .stream()
                .map(a -> a.getName())
                .collect(Collectors.toList());
    }
}

通过以上方法,开发者可以轻松获取PostgreSQL数据库表的列名,以便在Java Spring Boot应用程序中进行后续处理。

0