我刚刚开始探索 Spring Data JDBC。我有一个简单的数据库(postgres),其中包含我要查询的问卷表:
CREATE TABLE IF NOT EXISTS foster.questionnaires (
questionnaire_id SERIAL PRIMARY KEY,
version varchar(10),
name text,
title text,
description text,
status questionnaire_status_types
);
和 Java 类:
(配置灵感来自这里)
@SpringBootApplication(scanBasePackages= {"com.app.foster"})
@EnableJdbcRepositories("com.app.foster.dal.repositories")
public class FosterApplication extends JdbcConfiguration {
// Config
@Bean
NamedParameterJdbcOperations operations() {
return new NamedParameterJdbcTemplate(dataSource());
}
@Bean
PlatformTransactionManager transactionManager() {
return new DataSourceTransactionManager(dataSource());
}
@Value("${spring.datasource.url}")
private String url;
@Bean
@ConfigurationProperties("spring.datasource")
public HikariDataSource dataSource() {
//User name and password is fetched from some other data storage
HikariConfig hikariConfig = new HikariConfig();
hikariConfig.setJdbcUrl(url);
hikariConfig.setUsername("postgres"); //TODO: abstract these
hikariConfig.setPassword("password");
//The data source created here doesn't have connection timeout value
//set by me
return new HikariDataSource(hikariConfig);
}
@Bean
public ApplicationListener<?> loggingListener() {
return (ApplicationListener<ApplicationEvent>) event -> {
if (event instanceof RelationalEvent) {
System.out.println("Received an event: " + event);
}
};
}
public static void main(String[] args) {
SpringApplication.run(FosterApplication.class, args);
}
}
(实体)
@Entity
@Table(name="questionnaires")
public class Questionnaire {
@Id
Long questionnaire_id;
String version;
String name;
String title;
String description;
}
慕容3067478
BIG阳
相关分类