如何在没有jpa的情况下在spring boot中从oracle获取数据

Rop*_*din 2 java oracle spring-boot

我想在spring boot中从oracle数据库中获取数据,但我不想使用JPA。你能给我一个例子,我应该怎么做?谢谢你。

Pat*_*ick 5

在 Spring-Boot 中使用没有 JPA 的数据库,您可以使用 Spring-Boot 的 JDBC 启动器。

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
Run Code Online (Sandbox Code Playgroud)

对于 Oracle,您还需要使用 JDBC 驱动程序。例如这个:

<dependency>
    <groupId>oracle.jdbc</groupId>
    <artifactId>ojdbc7</artifactId>         
    <version>12.1.0.2</version>
    <classifier>jdk17</classifier>
</dependency>
Run Code Online (Sandbox Code Playgroud)

在 application.properties 文件中,您必须配置数据源:

spring.datasource.driverClassName=oracle.jdbc.driver.OracleDriver
spring.datasource.url=
spring.datasource.username=
spring.datasource.password=
Run Code Online (Sandbox Code Playgroud)

这就是配置所需的全部内容。要对数据库进行选择,您必须JdbcTemplate在任何 spring bean 类中自动装配。

@Component
public class DataDao {

    private final JdbcTemplate jdbcTemplate;

    public DataDao(JdbcTemplate jdbcTemplate) {
        super();
        this.jdbcTemplate = jdbcTemplate;
    }
Run Code Online (Sandbox Code Playgroud)

自动装配后,jdbcTemplate您可以查询数据库:

jdbcTemplate.query(yourQuery, RowMapper<?>);
Run Code Online (Sandbox Code Playgroud)