gpt4 book ai didi

java - 使用 JdbcTemplate 连接数据库

转载 作者:搜寻专家 更新时间:2023-10-30 20:16:57 24 4
gpt4 key购买 nike

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

应用类:

@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 类:

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
}

Controller 类:

@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(这可能是你的应用程序没有的原因),所以你可以使用你的 Autowiring 数据源自己创建它.. .

JdbcTemplate jdbcTemplate = new JdbcTemplate( dataSource );

... 或者在您的 spring 配置中将其定义为一个 bean 并 Autowiring 它。

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

关于java - 使用 JdbcTemplate 连接数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34491434/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com