Spring整合JDBC
spring是一个容器。
Spring 有一个jar包提供了一个叫做JDBCTemplate模板,所以他能对数据库操作,spring还提供了很多模板,针对hibernate、Mybatis模板。JDBCTemplate跟Dbutils中的QueryRunner极度相似
整合JDBC(手动创建对象)
1. 导包
C3p0,JDBC驱动包 spring-jdbc spring-tx

2. 使用它就是使用一个jdbcTemplate模板对数据库进行操作,需要数据库连接
给他连接 Connection 给一个 dataSource
ComboPooledDataSource dataSource = new ComboPooledDataSource(); dataSource.setDriverClass("com.mysql.jdbc.Driver"); dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/springjdbc"); dataSource.setUser("root"); dataSource.setPassword("root");
JdbcTemplate jdbcTemplate = new JdbcTemplate(); jdbcTemplate.setDataSource(dataSource); String sql = "INSERT INTO t_user(uname,ubalance) VALUES ('张三',1000)"; jdbcTemplate.update(sql);
|
spring管理对象的方式
UserDao 接口 UserDaoImpl 实现类 applicationContext.xml

使用spring管理对象开发,一定要搞清楚对象之间的依赖关系。
将对应的bean类配置到配置文件中 将属性的注入写好
<!--dataSource数据库 --> <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"></property> <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/springjdbc"></property> <property name="user" value="root"></property> <property name="password" value="root"></property> </bean> <!--数据库连接池--> <bean name="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"></property> </bean> <!--dao--> <bean name="userDao" class="cn.hd.springJDBC.impl.UserDaoImpl"> <!--dao中set的--> <property name="jt" ref="jdbcTemplate"></property> </bean> |
springJdbcApi
增删改: 调用JdbcTemplate update方法 如果有参数 直接按照顺序写在方法后面即可。
String sql = "INSERT INTO t_user(uname,ubalance) VALUES (?,?)"; int update = jt.update(sql, user.getUname(), user.getUbalance()); |
查询调用: 调用 jdbcTemplate query 方法 参数同上,。结果及的处理,要传一个RowMapper匿名内部类
String sql = "select * from t_user"; List<User> list = jt.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; } }); |
Spring 提供了一个父类 JdbcDaoSupport 这个父类中提供了JdbcTemplate模板,在实现dao类时,可以直接使用,并且在配置bean时,依赖关系改变,在实现dao类时直接依赖于dataSource。
Spring读取配置文件
db.properties 书写配置文件时要注意 键名要加前缀,比避免和关键字冲突。
如何读取配置文件 在 applicationContext.xml 中加上一条配置
<context:property-placeholder location="classpath:cn/hd/springJDBC/db.properties"></context:property-placeholder> |
Location 是配置文件的地址
获得配置文件中的信息
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <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> </bean> |