📜  Spring Boot JDBC 的优点

📅  最后修改于: 2022-05-13 01:54:57.008000             🧑  作者: Mango

Spring Boot JDBC 的优点

Spring JDBC用于构建企业应用程序的数据访问层,它使开发人员能够连接到数据库并编写 SQL 查询并将数据更新到关系数据库。与数据库相关的代码必须放在 DAO 类中。 SpringJDBC 提供了一个名为JdbcTemplate的类来处理数据库相关的逻辑。 JdbcTemplate 是 JDBC 技术之上的抽象层。 JdbcTemplate 内部使用 Jdbc 代码,但提供了 API,因此开发人员不必编写 Boiler Plate 代码。

为什么要使用 Spring Boot JDBC?

Spring Boot JDBC 在功能上与 Spring JDBC 相似,但 Spring Boot JDBC 在实现上有所不同。由于 Spring boot 遵循约定优于配置,因此在 spring boot.in 中实现 JDBC 更简单。

使用 SpringJDBC 优于传统 JDBC API 的优势

  • Spring 在 JDBC 包中提供了org.springframework.jdbc.core.JdbcTemplate类,可以自动释放数据库连接。
  • JdbcTemplate 提供了一个很好的异常处理机制,更具体地处理数据库,它将标准的 JDBC SQLExceptions 转换为通用且信息更丰富的 RuntimeExceptions,让开发人员更好地识别错误。
  • RowMapper 或 ResultSetExtractor 是 JdbcTemplate 通常使用的接口,用于在 ResultSet 的每行的基础上映射一行,它允许将 SQL 结果直接转换为对象或对象列表。
  • JdbcTemplate 提供了直接编写 SQL 查询的方法,从而节省了大量工作,API 层避免了在 JDBC 程序中使用样板代码。

Spring Boot JDBC 相对于 Spring JDBC 的一些优势

JDBC Using Spring Boot

JDBC Using Spring

Only one spring-boot-starter-jdbc dependency is required to make available all the Spring modules we need to perform JDBC operations.Multiple dependencies like spring context and spring JDBC must be included in order to perform JDBC operations.
In spring boot we do not have to explicitly register template beans PlatformTransactionManager, JdbcTemplate, NamedParameterJdbcTemplate spring boot will create it for you automatically if not created.The template beans PlatformTransactionManager, JdbcTemplate, NamedParameterJdbcTemplate must be registered in order to use JDBC in your application. 
It auto-initializes data source bean if not mentioned explicitly and you can set the spring.datasource.initialize to false if you don’t want to use the bean. In spring JDBC, it is required to create a database bean either using XML or javaconfig.
Any database initialization script like deleting or creating a table in the .sql file gets executed automatically in spring boot JDBC.Any database script in the .sql files needs to be given in the configuration file for it to work in spring JDBC.