I am new to Springs MVC and I tried to integrate HikariCP with JdbcTemplate. But got lot of errors any help, how to point JdbcTemplate to HikariCP DataSource.
in applicationContext.xml
<bean id="dataSource" class="com.zaxxer.hikari.HikariConfig">
<property name="poolName" value="springHikariCP" />
<property name="connectionTestQuery" value="SELECT 1" />
<property name="dataSourceClassName" value="com.mysql.jdbc.jdbc2.optional.MysqlDataSource" />
<property name="dataSourceProperties">
<props>
<prop key="url">${jdbc.url}</prop>
<prop key="user">${jdbc.username}</prop>
<prop key="password">${jdbc.password}</prop>
</props>
</property>
</bean>
<bean id="jdbcTemplate" class="com.zaxxer.hikari.HikariDataSource" destroy- method="close">
<property name="dataSource" ref="dataSource"></property>
</bean>
And in controller:
Controller public class HandleWareHouse{
private DataSource dataSource;
private JdbcTemplate jdbcTemplate;
public void setDataSource(DataSource dataSource){
this.dataSource = dataSource;
}
@RequestMapping(value="/saveProduct_categories", method = RequestMethod.POST)
@ResponseBody
public String insertPc(@RequestParam Map<String,String> requestParams){
jdbcTemplate = new JdbcTemplate(dataSource);
String sql = "INSERT INTO product_categories(name,code,des,grp_name) VALUES(?,?,?,?)";
jdbcTemplate.update(sql, new Object[] {requestParams.get("pname"),requestParams.get("pcode"),requestParams.get("stext"),requestParams.get("pcategory")});
return "sucess";
}
}
But getting error as shown below:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jdbcTemplate' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Initialization of bean failed; nested exception is org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'com.zaxxer.hikari.HikariConfig' to required type 'javax.sql.DataSource' for property 'dataSource'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [com.zaxxer.hikari.HikariConfig] to required type [javax.sql.DataSource] for property 'dataSource': no matching editors or conversion strategy found
答案 0 :(得分:1)
我使用spring javaconfig配置数据源并获取jdbctemplate。我认为这是最好的
@Bean
public DataSource getDataSource() {
private HikariDataSource dataSource() {
final HikariDataSource ds = new HikariDataSource();
ds.setMaximumPoolSize(100);
ds.setDriverClassName("oracle.jdbc.driver.OracleDriver");
ds.setJdbcUrl("jdbc:oracle:thin:@localhost:1521:XE"); ;
ds.setUsername("username");
ds.setPassword("password");
return ds;
}
}
@Bean
public JdbcTemplate getJdbcTemplate() {
return new JdbcTemplate(getDataSource());
}
我希望这对你有用。