我正在尝试使用 Spring JDBCTemplate 类来访问数据库。作为第一个教程,我使用了 xml spring 配置文件,一切都按预期工作。现在,我尝试使用@Configuration,创造DataSource并JdbcTemplate通过实例@Bean在此文件中的注释。但是,我在int result = template.update(sql);
我确定我犯了一个愚蠢的错误。想知道它可能是什么。
代码如下。
@Configuration
public class SpringJDBCAnnotation {
@Autowired
static JdbcTemplate template;
@Autowired
static DataSource dataSource;
@Bean
DataSource dataSource() {
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql://localhost:3306/organization");
ds.setUsername("root");
ds.setPassword("test");
return ds;
}
@Bean
JdbcTemplate template() {
JdbcTemplate template = new JdbcTemplate();
template.setDataSource(dataSource);
return template;
}
public static void main(String[] args) {
String sql = "insert into employee values(1, 'Tom', 'Cruise')";
int result = template.update(sql);
System.out.println("# of records inserted : " + result);
}
}
不负相思意
相关分类