0

If i do the code in controller with

final DataSource dataSource = (DataSource) getApplicationContext().getBean("dataSource", DataSource.class);
final JdbcTemplate jdbcTemplate = new JdbcTemplate(jdbcDataSource);
final NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(jdbcTemplate);

This will work fine

If i have to attain the same in Spring application context

<bean id="jdbcTemplate"  class="org.springframework.jdbc.core.JdbcTemplate" autowire="constructor" />  

<bean class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate"
      id="namedParameterJdbcTemplate">  
    <constructor-arg ref="jdbcTemplate" />
</bean> 

In Hibernate Repository Class

private NamedParameterJdbcTemplate namedParameterJdbcTemplate; 
public void setNamedParameterJdbcTemplate(NamedParameterJdbcTemplate namedParameterJdbcTemplate) {  
    this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;  
} 

This throws error

Is there any way to make the object namedParameterJdbcTemplate working in Repository class

JamesENL
  • 6,400
  • 6
  • 39
  • 64
Arun b
  • 1
  • 1
  • If i was to guess, in your Hibernate Repository class, it doesn't look like namedParameterJdbcTemplate is initialized to anything, which may be why its throwing a Null Pointer... – ryekayo Mar 18 '15 at 20:49
  • "This throws error" doesn't help us. Show us the error and stack trace. – skaffman Mar 18 '15 at 21:05
  • @ryekayo If you dont mind , can you show with a example – Arun b Mar 18 '15 at 22:43

1 Answers1

0

If you've declared your jdbcTemplate in your XML, that is all you should need.

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

You do need to set the datasource on the JdbcTemplate though.

Once you autowire the JdbcTemplate into your DAO, you should be able to use that to create a NamedParameterJdbcTemplate.

@Repository
public class DAOImpl implements DAO {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    public void foo() {
        NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(jdbcTemplate);
        ....
    }
}

You need to actually create an instance of it before you use it.

If you want to use XML to create your instance you can do that too, but you'll need to autowire in the instance that gets created by the XML.

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

<bean id="namedParamterJdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
   <constructor-arg ref="jdbcTemplate"/>
</bean>

Then you should only have to autowire in the NamedParameterJdbcTemplate into your DAO.

JamesENL
  • 6,400
  • 6
  • 39
  • 64