简体   繁体   中英

How do I add JDBI into a Spring Boot application?

I am trying to set up a Spring Boot application without Hibernate and use JDBI instead. Now I use maven as my package management but I am unsure how to get this done. Here you can see part of pom.xml . I found some info with gradle but could someone show me how JBDI can be integrated with maven package management? At the same time is there an example how to add connect it to a SQLite db.

  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
      <exclusions>
        <exclusion>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-tomcat</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-jetty</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.jayway.jsonpath</groupId>
      <artifactId>json-path</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.jdbi</groupId>
      <artifactId>jdbi</artifactId>
      <version>2.78</version>
    </dependency>
   </dependencies>

You can see a runnable code example and explanation here https://www.surasint.com/spring-boot-database-transaction-jdbi/

Basically, you need this dependency for spring database, jdbi, and Mysql connector in pom.xml

    <!-- for db annotation, ex @Transactional -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <!-- mysql connector -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.10</version>
    </dependency>
    <!-- jdbi: db table mapper -->
    <dependency>
        <groupId>org.jdbi</groupId>
        <artifactId>jdbi</artifactId>
        <version>2.62</version>
    </dependency>
</dependencies>

Then you need a datasource from Spring. You can do like this:

@Qualifier("dataSource")
@Autowired
private DataSource dataSource;

Then you need a connection from that datasource.

Connection conn =  DataSourceUtils.getConnection(dataSource);

Then hook the conneciton with JDBI.

Handle handle = DBI.open(conn);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM