基于struts2+hibernate+spring实现数据库字段的自动增长,格式为时间+自增长数据。
(1)查询数据库表,属性的最大值(数据库为oracle10G)
/**
* 查询最大的一个自增长的号(格式:时间+自增长)
* 用作帐卡或其它自增长的操作(格式:时间+自增长)
* @param str 表字段
* @Param tables 表名称
* @return 最大的一个号
*/
private String getMaxZhkBh(final String str, final String tables){
String max=(String)getHibernateTemplate().execute(new HibernateCallback(){
public Object doInHibernate(Session session) throws HibernateException, SQLException {
String hql="select max("+str+") from "+tables+" as w where substr("+str+",0,8)="+TimeStamp.getTime();
Query q=session.createQuery(hql);
List all=q.list();
if(all!=null&&all.size()>0){
return all.get(0);
}
return null;
}
});
return max;
}
(2) 自增长数一般都是001,002,003 以下方法就是增长时不够位数补零操作,当然了几位由你自己定义了。
/**
* 不够补零操作
* @param a 数
* @param len 长度
* @return
*/
public String format(int a ,int len){
String temp=String.valueOf(a);
while(temp.length()<len){
temp="0"+temp;
}
return temp;
}
(3)以下是要在Action中要调用的方法。数据库第一次操作查询最大值时,是没有的,所以必须指定一个值001,以后操作就可以查询最大值,然后在最大值上自增长1个。
/**
* 生成自增长号
* @param str 表字段
* @param tables 表名
* @return 新的号
*/
public String getTimeStamp(String str,String tables){
String max=getMaxZhkBh(str,tables);
String stamp=null;
if(max==null){
stamp=TimeStamp.getTime()+"-"+"001";
}else{
String sub=max.substring(max.lastIndexOf("-")+1);
int i=Integer.parseInt(sub)+1;
String temp=this.format(i, 3);
stamp=TimeStamp.getTime()+"-"+temp;
}
return stamp;
}
(4) TimeStamp.getTime()就是取得时间格式内容,代码如下。
public class TimeStamp extends HibernateDaoSupport{
public TimeStamp() {
}
/**
* Gets the time.
*
* @return the time
*/
public static String getTime(){
String temp = null ;
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd") ;
temp = sdf.format(new Date()) ;
return temp ;
}
}