发表于: 2017-08-15 23:31:21
1 896
一、今日完成
1)在spring配置文件中定义JdbcTemplate,生成一个applicationContext.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!--扫描包以注册注解声明的Bean-->
<context:component-scan base-package="induction" />
<!--数据库连接池-->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/task01"/>
<property name="username" value="acer"/>
<property name="password" value="xyz"/>
<!--连接池的最大数据库连接数-->
<property name="maxActive" value="255"/>
<!--最大等待连接中的数量-->
<property name="maxIdle" value="5"/>
<!--最大等待毫秒数-->
<property name="maxWait" value="10000"/>
</bean>
<!--配置Jdbc Template-->(声明一个抽象的<Bean>,以便所有的DAO复用jdbctemplate)
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
其中,maxActive、maxIdle、MaxWait、queryTimeout(查询数据的时的最大超时时间)、fetchSize(每次从数据库返回到内存的行数)等属性用来控制底层JDBC API的属性。
2)基本的增删查改与其他数据库操作
package com.jnshu.induction.dao;
import *
@Repository //通过spring注释定义一个DAO
public class PersonDao {
private JdbcTemplate jdbcTemplate;
@Autowired //自动注入IdbcTemplate的Bean
public void setJdbcTemplate (JdbcTemplate jdbcTemplate){
this.jdbcTemplate = jdbcTemplate;
}
/*定义基本的数据操作*/
//插入一条记录
public void addtOne (Person one){
String sql = "INSERT INTO person (id, name, gender, birth_date, country) VALUES(?, ?, ?, ?, ?) ";
Object [ ] params = new Object[] {one.getId(), one.getName(), one.getGender(), one.getBirth_date(), one.getCountry()};
jdbcTemplate.update(sql, params, new int[]{Types.INTEGER, Types.VARCHAR, Types.VARCHAR, Types.DATE, Types.VARCHAR});
}
//根据id查询一条记录并从结果集中返回该记录
public List<Person> getOne(final int oneId){
String sql="SELECT * WHERE name=?";
final Person one = new Person();
jdbcTemplate.query(sql, new Object[ ] { oneId } ), new RowCallbackHandler(){
public void processRow (ResultSet rs) throws SQLException{
one.setId(oneId);
one.setName(rs.getString("name"));
one.setGender(rs.getString("gender");
one.setBirth_date(rs.getDate("birth_date"));
one.setCountry(rs.getString("country"));
}
return one;
};
其他如批量更改数据、调用存储过程等操作都可以通过过JdbcTemplate提供的接口方法实现。
二)明日计划
在DAO中定义删除、更改表记录的方法,掌握相关接口调用方法,然后编写业务层service和一个JUnit单元测试,提交任务1.
三)遇到的问题
JdbcTemplate提供的数据库增、删、查、改等接口方法目前还没有弄清楚,由于同一种数据库操作可用的方法比较多,而且各自用法不同,所以花了一些时间去验证方法该如何使用。
四)今日收获
学会在Spring配置文件中配置DAO的基本流程
1)定义DataSource
2)定义JdbcTemplate
3)声明一个抽象的<Bean>
4)配置具体的DAO.
评论