spring-boot - 我试图在 Spring Boot 应用程序中进行简单的 JDBC 调用不起作用
问题描述
我期待使用 Spring Boot 应用程序创建服务,我喜欢使用 JDBC 准备语句调用来执行存储过程,从而获得所需的结果。我喜欢连接池,但不幸的是,我不知道实现
概括
(使用spring boot的服务--->Simple JDBC with connection pooling---->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 的访问不能为空
预期结果:数据库数据应显示在 Web 浏览器中
这是我的 github存储库https://github.com/PradeepKumarHE/SpringBootWithSimpleJDBC/tree/master 我有 DBscript 文件要创建
解决方案
我从你的 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/ )
在这种情况下,您需要
- 在 maven 依赖项中声明了 mysql jdbc 驱动程序
- 在您的属性或 yaml 中定义 spring.datasource.url、spring.datasource.username、spring.datasource.password(如果您的 maven 部门中只有一个 jdbc 驱动程序,则不需要定义 spring.datasource.driver)
- 删除您的 DataSources 配置,因为 springboot 会为您自动配置它
推荐阅读
- javascript - 有谁知道如何将现有项目从 Sencha Ext JS 4.2 升级到最新的 Sencha Ext JS 版本?
- google-apps-script - 最后一个元素不包含在数组中的映射变量中
- ios - 构建反应原生 iOS 应用程序时出现 Clang 错误
- ios - 如何在 Swift 中从图像中录制视频而不会泄漏内存?
- bash - 在 bash/shell 中声明数组
- intershop - Intershop、页面缓存、PGID 和 OAuth2
- regex - 正则表达式:我需要提取除字符串 `ignore` 之外的所有单词
- reactjs - 在 ReactJs 中测试页面 beforeonload
- gstreamer - 来自内存变量的 Gstreamer 文本覆盖
- php - Laravel Eloquent 模型:自动创建值