Spring整合jdbc
Spring是一个容器。
Spring有个jar包提供了一个叫做JDBCTenplate模块,所以他能对数据库操作。Spring还提供了很多的模块
针对hibernate、Mybatis 模块。JDBCTemplte跟Ddutil中的QueryRunner极度相似。
整合JDBC(手动创建对象)
1.导包
2.使用一个jdbcTemplate模块对数据库进行操作
Spring管理对象的方式:
UserDao接口UserDaoImpl实现类 applicationContext.xml
使用spring管理对象开发,一定要搞清楚对象之间的依赖关系。
然后将bean配置到文件中,将属性的注入写好
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver?useUnicode=true&characterEncoding=utf-8"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring_jdbc"></property>
<property name="user" value="root"></property>
<property name="password" value="123"></property>
</bean>
<bean name="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean name="userDao" class="cn.hd.spring_jdbc.impl.UserDaoImpl">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
jdbcTemplateApi
增删改 JDBCTemplate update 方法,如果有参数,直接按照顺序写在后面即可。
int update = jdbcTemplate.update(sql, user.getUname(), user.getUbalance());
查询:调用JDBCTemplate query 方法 参数同上。结果集处理,要传一个RowMapper匿名内部类@Override
public List<User> getAll() {
String sql = "select *from t_user";
List<User> query = jdbcTemplate.query(sql, new RowMapper<User>() {
@Nullable
@Override
public User mapRow(ResultSet resultSet, int i) throws SQLException {
User user = new User();
user.setUid(resultSet.getInt("uid"));
user.setUname(resultSet.getString("uname"));
user.setUbalance(resultSet.getInt("ubalance"));
return user;
}
});
return query;
}
Spring 提供了一个父类,jdbcDaoSupport这个父类中提供了jdbcTemplate模块,并且配置bean类,依赖关系
改变,dao类时直接依赖于DateSource.
如何使用spring读取配置文件
db.properties 书写配置文件时要注意 键名必须要加前缀,避免和关键字重复。
如果读取配置文件 在applicationContexe.xml中加一条属性。注意使用context不能使用p标签,
context标签中包含p标签
xmlns:context="http://www.springframework.org/schema/context"
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
<!--读取db.properties文件-->
<context:property-placeholder location="classpath:cn/hd/spring_jdbc/db.properties"></context:property-placeholder>
location是配置文件的地址
获得配置文件中的信息
<property name="driverClass" value="${jdbc.driverClass}"></property>
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
<property name="user" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>