定时器
QUARTZ运行后的调用时间,只能往后设置,否则不运行
<bean id="statisTask" class="org.springframework.scheduling.timer.MethodInvokingTimerTaskFactoryBean">
<property name="targetObject" ref="对象"></property>
<property name="targetMethod" value="方法"></property>
</bean>
<bean id="scheduleStaTask" class="org.springframework.scheduling.timer.ScheduledTimerTask" >
<property name="timerTask" ref="statisTask"></property>
<property name="period" value="300000(间隔时间,单位为毫秒)"></property>
</bean>
<bean class="org.springframework.scheduling.timer.TimerFactoryBean">
<property name="scheduledTimerTasks">
<list>
<ref bean="scheduleStaTask"/>
</list>
</property>
</bean>
配置文件
Spring载入配置文件,如果是两个以上:
ApplicationContext ac = new ClassPathXmlApplicationContext(new String[]{"applicationContext.xml","dao.xml"});
或者用通配符:
ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:/*.xml");
数据库
表的操作
Execute 可以执行SQL语句,总是使用Statement,不接受参数,而且不返回影响记录的计数,更适合于create和drop表。
增、删和改
Update 方法返回的是受影响的记录数据的个数;如果传入参数的话,使用PreparedStatement,更适合于插入、更新和删除操作。
不带参数的更新
JdbcTemplate.update(“insert into user values(‘+user.getId()+” ’ , ’ ”+user.getName()+”’); ”)
带参数的更新
jdbcTemplate.update(“update user set name=? where user_id=?”, new Object[] {name, id});
getJdbcTemplate().update("DELETE FROM employee WHERE id = ?", new Object[] { employee.getId() });
jdbcTemplate.update("update customer set first_name=? where id=?",
new Object[] { "A", 1L }, new int[] { Types.VARCHAR, Types.INTEGER });
多条sql批量执行
jdbcTemplate.batchUpdate(new String[] { "update customer set first_name = 'FN#'","delete from customer where id > 2" });
PreparedStatement单个更新
jdbcTemplate.update(“带?的sql”,new PreparedStatementSetter() {
public void setValues(PreparedStatement ps) throws SQLException {
ps.setString(1,id); //只能访问外部的final变量
ps.setString(2,name);
}
});
PreparedStatement 批量更新
Public int[] insertUsers(final List users) {
String sql=”insert into user(name,age) values(?,?)”;
BatchPreparedStatementSetter setter=new BatchPreparedStatementSetter() {
Public void setValues(PreparedStatement ps,int i) throws SQLException {
User user=users.get(i);
Ps.setString(1, user.getName());
Ps.setInt(2,user.getAge());
}
Public int getBatchSize() {
Return users.size();
}
};
JdbcTemplate.batchUpdate(sql,setter);
}
查询
使用queryForXXX 的方法
JdbcTemplate.queryForList() 返回Map的列表,map使用column name作为key
Jdbc的callback方式—RowMapper
一次取得多条查询结果,将RS转换为java对象
多行查询:
class UserRowMapper implements RowMapper {
public Object mapRow(ResultSet rs,int index) throws SQLException
{
User u = new User();
u.setId(rs.getString("ID"));
u.setName(rs.getString("Name"));
u.setPassword(rs.getString("Password"));
return u;
}
}
// List 返回的是user对象的List
public List select(String where)
{
List list;
String sql = "select * from admin "+where;
list = jdbcTemplate.query(sql,new RowMapperResultReader(new UserRowMapper()));
return list;
}
单行查询:
Return (User) list.get(0);