首先看jdbctemplate配置
- <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
- <property name="dataSource"><ref bean="dataSource"/></property>
- </bean>
这个dataSource就不用说了吧,跟Hibernate使用同一个数据源
DAO层写法
- <bean id="serviceAnalyserJdbcDao" class="com.fruitking.dao.jdbcdao.impl.ServiceAnalyserDaoImpl">
- <property name="jdbcTemplate" ref="jdbcTemplate" />
- </bean>
service层写法
- <bean id="serviceAnalyserJdbcService" class="com.fruitking.service.jdbcservice.impl.ServiceAnalyserServiceImpl">
- <property name="serviceAnalyserJdbcDao" ref="serviceAnalyserJdbcDao" />
- </bean>
Spring配置就是这么简单了
当然在DAO层的程序里面我们一般使用一个对象包装
- import org.springframework.jdbc.core.RowMapper;
- import org.springframework.jdbc.core.support.JdbcDaoSupport;
- import com.fruitking.dao.jdbcdao.IAccessAnalyserDao;
- import com.fruitking.entity.AccessAnalyser;
- public class AccessAnalyserDaoImpl extends JdbcDaoSupport implements IAccessAnalyserDao{
- public List<AccessAnalyser> countGroupByYear(){
- String sql ="select to_char(t.createddate, 'yyyy') as cyear, count(*) as yearcount from accessanalyser t group by to_char(t.createddate, 'yyyy')";
- List<AccessAnalyser> accessAnalyserList = this.getJdbcTemplate().query(sql, new AccessAnalyserRowMapper());
- return accessAnalyserList;
- }
- class AccessAnalyserRowMapper implements RowMapper {
- public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
- AccessAnalyser accessAnalyser = new AccessAnalyser();
- accessAnalyser.setYearName(rs.getString("cyear"));
- accessAnalyser.setClickTimes(rs.getLong("yearcount"));
- return accessAnalyser;
- }
- }
- }
这样就可以像Hibernate一样在Spring框架中使用JDBC了,只不过你可以任意的使用JDBC的东西
【编辑推荐】