
Originally Posted by
driesva
Thanks, that saved me searching for that link !
Also, you bernardbjr, you really shouldnt be doing a getBean within your code.
Your class that is using the datasource should have the datasource injected into it by Spring, so within your code you just have a private datasource field with a setter on it, and then you make your code that is using the datasource a Spring bean.
Also, it's rare in Spring nowadays to have to use a datasource directly at all. Have a look at the JDBC section of the manual. There are a lot of Spring classes that hide datasource and connection handling from you, so you just concentrate on coding the data access bits.
for example, look at the code below, the jdbcTemplate is autowired in, the class below is a DAO Spring bean because I have annotated it as such with @Repository, and the jdbcTemplate itself is defined in an application context with the datasource wired in to it there. As you can see, not a datasource in sight in the code itself:
Code:
package blog.jdbc.dao;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.stereotype.Repository;
import blog.jpa.domain.Restaurant;
import blog.jpa.domain.RestaurantDao;
@Repository
@Qualifier("JdbcRestaurantImpl")
public class JdbcRestaurantDao implements RestaurantDao {
@Autowired
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
@SuppressWarnings("unchecked")
public List<Restaurant> findByName(String name) {
SearchParameters search = new SearchParameters();
search.setName(name);
SqlParameterSource namedParameters = new BeanPropertySqlParameterSource(search);
return namedParameterJdbcTemplate.query(
"select id,name,address_id from restaurant where name = :name",
namedParameters,new BeanPropertyRowMapper(Restaurant.class)
);
}
}
NB, the above code has a direct relationship with the code here (just nodding my hat):
http://blog.springsource.com/2006/05...-in-spring-20/
I was giving a course on persistence and did the same thing three times, once with JDBC, once with Hibernate, and once with JPA.