【问题标题】:Am trying to do simple JDBC call in a spring boot application is not working我试图在 Spring Boot 应用程序中进行简单的 JDBC 调用不起作用
【发布时间】:2019-07-20 17:45:05
【问题描述】:

我期待使用 Spring Boot 应用程序创建服务,我喜欢使用 JDBC 准备语句调用来执行存储过程,从而获得所需的结果。 我喜欢有连接池,但不幸的是,我不知道实现

总结

(使用spring boot的服务--->带有连接池的简单JDBC---->Mysql)

为此,我尝试创建数据源并执行 jdbc 语句但不起作用

@Controller
public class ExampleController {

    @Autowired
    private ExampleRepository repo;

    @RequestMapping("/")
    public @ResponseBody String getDataBaseData() throws SQLException{
        return repo.getDataBaseData();
    }
}

@Configuration
public class DataSources {
    @Bean(name = "primary")
    @Primary
    @ConfigurationProperties(prefix="spring.datasource")
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create().build();
    }
}

@Component
public class ExampleRepository {

    @Autowired
    private DataSource ds;

    public String getDataBaseData() throws SQLException {
        Connection con = ds.getConnection();
        System.out.println(con);
        Statement stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery("select * from emp");
        while (rs.next())
            System.out.println(rs.getInt(1) + "  " + rs.getString(2) + "  " + rs.getString(3));
        con.close();
        return rs.toString();
    }
}

出现如下错误

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: 无法创建与数据库服务器的连接。

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: 无法创建与数据库服务器的连接。

在类路径资源 [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class] 中定义名称为“entityManagerFactory”的 bean 创建错误:调用 init 方法失败;嵌套异常是 org.hibernate.HibernateException:当未设置“hibernate.dialect”时,对 DialectResolutionInfo 的访问不能为空

预期结果:数据库数据应显示在网络浏览器中

这是我的 github 仓库https://github.com/PradeepKumarHE/SpringBootWithSimpleJDBC/tree/master 我在哪里创建 DBscript 文件

【问题讨论】:

  • “不工作”是什么意思?

标签: spring-boot


【解决方案1】:

我可以从你的 pom.xml 中看到,你正在使用 spring-boot-starter-data-jpa。它获取不必要的依赖项,这会触发 SpringBoot jpa 自动配置。 如果你想在 spring boot 中使用纯 jdbc,请将 spring-boot-starter-data-jpa 替换为 spring-boot-starter-jdbc (https://mvnrepository.com/artifact/org.springframework.boot/)

在这种情况下你需要

  1. 在 maven 依赖项中声明了 mysql jdbc 驱动程序
  2. 在你的属性或yaml中定义spring.datasource.url、spring.datasource.username、spring.datasource.password(如果你的maven deps中只有一个jdbc驱动,你不需要定义spring.datasource.driver )
  3. 删除您的 DataSources 配置,因为 springboot 会为您自动配置它

【讨论】:

  • 我没有得到3点,如何在java类中获取mysql连接对象
  • 如果我想连接两个不同的数据库怎么办
猜你喜欢
  • 2019-03-14
  • 2018-11-27
  • 2016-07-01
  • 2018-03-15
  • 2021-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多