使用 JdbcTemplate 连接数据库

Connection to database with JdbcTemplate

我正在尝试使用 jdbc 模板创建 table (h2)。当我在 UsersDAOImpl class 中执行不同的查询时一切正常,但是当我尝试首先在 Application class 中创建 table 时,JdbcTemplate 无法连接到数据库。我读到我需要添加依赖组 spring-boot-starter-jdbc 它将自动生成数据源到 我的 JdbcTemplate 应该连接,但似乎不起作用。我想我错过了什么,但找不到什么。

申请class:

@SpringBootApplication
public class Application implements CommandLineRunner  {

public static void main(String[] args) throws Exception{
    SpringApplication.run(Application.class, args);
}
 //doesn't create db alone;
@Autowired
JdbcTemplate jdbcTemplate;


@Override
public void run(String... arg0) throws Exception {
    jdbcTemplate.execute("DROP TABLE test IF EXISTS");
    jdbcTemplate.execute("CREATE TABLE test( id int(11), name VARCHAR(255),      role VARCHAR(255))");
}
}

UsersDAOImpl class:

public class UsersDAOImpl implements UsersDAO {

private DataSource dataSource;

public void setDataSource(DataSource dataSource) {
    this.dataSource = dataSource;
}
//and some additional methods to work with the database
}

控制器class:

@RestController
class Controller {  

    ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
    UsersDAO userDAO = ctx.getBean("userDAO", UsersDAO.class);
 //making the mapping
}

spring.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="userDAO" class="hello.UsersDAOImpl">
    <property name="dataSource" ref="dataSource" />
</bean>

<bean id="dataSource" 
      class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="org.h2.Driver" />
    <property name="url" value="jdbc:h2:~/test" />
    <property name="username" value="sa" />
    <property name="password" value="" />
</bean>

pom.xml:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
    </dependency>   
</dependencies>

您似乎在 spring 配置中定义了一个数据源(这就是 DAO 工作的原因),但没有 JdbcTemplate(这可能是您的应用程序不工作的原因),因此您可以自己创建它使用您的自动装配数据源...

JdbcTemplate jdbcTemplate = new JdbcTemplate( dataSource );

... 或在您的 spring 配置中将其定义为 bean 并自动装配它。

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    <property name="dataSource" ref="dataSource"/>
</bean>

在您的 Application.java class 中添加以下代码片段,并添加 dml(数据操作查询)、ddl(数据定义查询)脚本分别在 dml.sql 和 ddl.sql 文件中,确保它们都在 class 路径中可用。

删除 jdbcTemplate 声明和 运行() 方法。

@Bean
public JdbcTemplate jdbcTemplate() {
   return new JdbcTemplate(dataSource());
}

/**
 * Spring provided H2 Embedded Database. Read the dbscript and initiates the Database with the name H2-Test-DB.
 *
 * @return
 */
@Bean(name = "dataSource")
public DataSource dataSource(){
    EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
    builder.setName("H2-Test-DB");
    EmbeddedDatabase db = builder.setType(EmbeddedDatabaseType.H2)
            .addScript("classpath:db-script/ddl.sql")
            .addScript("classpath:db-script/dml.sql").build();
    log.info("Initiating the database from dbscript.");
    return db;

}

你的UsersDAOImpl .java应该是这样的。

public class UsersDAOImpl implements UsersDAO {

 @Autowired
 private JdbcTemplate jdbcTemplate;

 //and some additional methods to work with the database
}

找不到代码的确切问题,但有有效的解决方案:

The simplest way to configure a DataSource in Spring Boot is to create an application.properties file under src/main/resources with the following content (may need to update it with correct url, username and password):

spring.datasource.url=jdbc:mysql://localhost/:3306/databasename
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

进一步阅读可以在这个问题中找到:spring boot autoconfiguration with jdbc template autowiring dataSource issue

在这种情况下,答案和评论非常有帮助。