首页 > 解决方案 > JDBC 模板问题 Nullpointer 异常

问题描述

我试图在我的 Spring Boot 项目中使用 JDBCTemplate 连接到 postgresql 数据库,但是当我尝试进行查询时出现空指针异常

应用程序属性

spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://url/test
spring.datasource.username=postgres
spring.datasource.password=pass

Pom.xml

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>               
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
         <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
    </dependencies>

代码

public class TestDaoImpl implements TestDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Override
    public void testconnection() throws Exception {
        // TODO Auto-generated method stub
  
        int x=jdbcTemplate
        .queryForObject("select count(*) from table", Integer.class);
        System.out.println(x);
        
    
    }

我无法检测出什么问题...请您帮帮我...提前致谢!

标签: springspring-bootjdbctemplate

解决方案


@Bean
public JdbcTemplate jdbcTemplate(Datasource datasource){
    JdbcTemplate jdbcTemplate = new JdbcTemplate(datasource);
    return jdbcTemplate;
}

您可以使用数据源配置 jdbcTemplate,然后您可以自动装配它。

您可以将代码块放入配置类


推荐阅读