未分类
2020-12-07 09:55:31
1822677238@qq.com
手机扫码查看
2020java框架教程:jdbcTemplate的使用
1.创建项目
2.导包

3.日志文件
4.创建数据库表
5.创建工具类并连接数据库
6.创建实体类、dao、service以及实现类
使用JdbcTemplate
查询所有:
public List<Role> getAllList() {
try{
return jt.query("select*from role", new RowMapper<Role>() {
@Override
public Role mapRow(ResultSet rs, int i) throws SQLException {
return roleMapper(rs);
}
});
}catch (Exception e){}
return null;
}
查询单个
public Role getID(int id) {
try{
return jt.queryForObject("select*from role where id=?", new RowMapper<Role>() {
@Override
public Role mapRow(ResultSet rs, int i) throws SQLException {
return roleMapper(rs);
}
},id);
}catch (Exception e){}
return null;
}
封装Mapper方法
public Role roleMapper(ResultSet rs){
Role r=new Role();
try {
r.setId(rs.getInt("id"));
r.setNames(rs.getString("names"));
r.setNames2(rs.getString("names2"));
return r;
} catch (Exception e) {}
return null;
}
使用spring管理对象和对象间的依赖
<context:property-placeholder location="classpath:database.properties"/>
<!-- 连接池 -->
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${driver}"/>
<property name="jdbcUrl" value="${url}"/>
<property name="user" value="${username}"/>
<property name="password" value="${password}"/>
</bean>
<!-- JDBCTemplate -->
<bean name="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- roleDao -->
<bean name="roleDao" class="dao.impl.RoleDaoImpl">
<property name="jt" ref="jdbcTemplate"/>
</bean>



发表回复