我正在尝试使用jdbcTemplate创建表(h2)。当我在UsersDAOImpl类中执行不同的查询时,一切正常,但是当我尝试在Application类中首先创建表时,JdbcTemplate无法连接到数据库。我读到我需要添加依赖项组spring-boot-starter-jdbc,它将自动生成dataSource来连接我的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
}
控制器类:
@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 Boot中配置数据源的最简单方法是在src / main / resources下创建一个application.properties文件,其内容如下(可能需要使用正确的url,用户名和密码进行更新):
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
可以在以下问题中找到进一步的阅读:具有jdbc模板的autobooting dataSource问题的Spring Boot自动配置
在这种情况下,答案和评论非常有帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句