JAVA流水号生成, 支持数据库查询,Spring注入_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > JAVA流水号生成, 支持数据库查询,Spring注入

JAVA流水号生成, 支持数据库查询,Spring注入

 2012/2/24 9:58:30  numen06  程序员俱乐部  我要评论(0)
  • 摘要:packagecom.wesley.framework.dao;importjava.text.DecimalFormat;importjava.text.SimpleDateFormat;importjava.util.Date;importjava.util.HashMap;importjava.util.Map;importorg.apache.commons.dbcp.BasicDataSource;importorg.springframework.beans.factory.xml
  • 标签:Java Spring 数据库 数据
package com.wesley.framework.dao;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;

import com.wesley.framework.dao.dbutils.DBHelper;

public class PrimaryGenerater {

	private static PrimaryGenerater primaryGenerater = null;
	private DBHelper<PrimaryBean> dbHelper;
	private Map<String, String> sqls = new HashMap<String, String>();
	private Map<String, PrimaryBean> primarBeans = new HashMap<String, PrimaryBean>();

	private PrimaryGenerater() {
		super();
	}

	public PrimaryGenerater(BasicDataSource database, Map<String, String> sqls) {
		super();
		this.dbHelper = new DBHelper<PrimaryBean>(database, PrimaryBean.class);
		this.sqls = sqls;
		for (String key : sqls.keySet()) {
			this.primarBeans.put(key, this.getPrimaryBeanByDatabase(key));
		}
	}

	public static PrimaryGenerater newInstance(BasicDataSource database,
			Map<String, String> sqls) {
		synchronized (PrimaryGenerater.class) {
			primaryGenerater = new PrimaryGenerater(database, sqls);
		}
		return primaryGenerater;
	}

	/**
	 * 
	 * 取得PrimaryGenerater的单例实现
	 * 
	 * @return
	 */
	public static PrimaryGenerater getInstance() {
		if (primaryGenerater == null) {
			synchronized (PrimaryGenerater.class) {
				if (primaryGenerater == null) {
					primaryGenerater = new PrimaryGenerater();
				}
			}
		}
		return primaryGenerater;
	}

	/**
	 * 通过 数据库查询键获得封装类
	 * 
	 * @param key
	 * @return
	 */
	public synchronized PrimaryBean getPrimaryBeanByDatabase(String key) {
		if (!this.sqls.containsKey(key))
			return null;
		PrimaryBean primaryBean = this.primarBeans.get(key);
		if (primaryBean != null && !primaryBean.getIsDataBase())
			return primaryBean;
		primaryBean = dbHelper.query(this.sqls.get(key));
		return primaryBean;
	}

	/**
	 * 通过数据库查询键位生成流水号
	 * 
	 * @param key
	 * @return
	 */
	public synchronized String geneterNextNumberByKey(String key) {
		PrimaryBean primaryBean = this.getPrimaryBeanByDatabase(key);
		return this.geneterNextNumber(primaryBean);
	}

	/**
	 * 通过封装类生成流水号
	 * 
	 * @param primaryBean
	 * @return
	 */
	public synchronized String geneterNextNumber(PrimaryBean primaryBean) {
		String nextNumber = this
				.geneterNextNumber(primaryBean.getStartNumber());
		primaryBean.setStartNumber(nextNumber);
		String dataString = this.geneterDataString(primaryBean.getDataString());
		String serialNumber = primaryBean.getPrefix() + dataString + nextNumber;
		return serialNumber;
	}

	/**
	 * 通过开始数字字符串生成下一个流水号
	 * 
	 * @param startNumber
	 * @return
	 */
	public synchronized String geneterNextNumber(String startNumber) {
		Long temp = Long.valueOf(startNumber) + 1;
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < startNumber.length(); i++)
			sb.append("0");
		DecimalFormat df = new DecimalFormat(sb.toString());
		return df.format(temp);
	}

	/**
	 * 通过 格式生成日期格式
	 * 
	 * @param dataformat
	 * @return
	 */
	private synchronized String geneterDataString(String dataformat) {
		SimpleDateFormat formatter = new SimpleDateFormat(dataformat);
		return formatter.format(new Date());
	}

	public static void main(String[] args) throws Exception {
		XmlBeanFactory context = new XmlBeanFactory(new ClassPathResource(
				"applicationContext.xml"));
		BasicDataSource dataSource = (BasicDataSource) context
				.getBean("dataSource");
		Map<String, String> map = new HashMap<String, String>();
		map.put("new",
				"select 'SP-' as prefix,'yyyyMMdd' as dataString,'000000' as startNumber from business union select 'SP-' as prefix,'yyyyMMdd' as dataString,'000000' as startNumber");
		PrimaryGenerater.newInstance(dataSource, map);
		for (int i = 0; i < 100; i++) {
			System.out.println(PrimaryGenerater.getInstance()
					.geneterNextNumberByKey("new"));
		}
	}

}

package com.wesley.framework.dao;

public class PrimaryBean {
	// select 'SP-' as prefix,'yyyyMMdd' as dataString,'000000' startNumber
	private String prefix;
	private String dataString;
	private String startNumber;
	private Boolean isDataBase = false;

	public String getPrefix() {
		return prefix;
	}

	public void setPrefix(String prefix) {
		this.prefix = prefix;
	}

	public String getDataString() {
		return dataString;
	}

	public void setDataString(String dataString) {
		this.dataString = dataString;
	}

	public String getStartNumber() {
		return startNumber;
	}

	public void setStartNumber(String startNumber) {
		this.startNumber = startNumber;
	}

	public Boolean getIsDataBase() {
		return isDataBase;
	}

	public void setIsDataBase(Boolean isDataBase) {
		this.isDataBase = isDataBase;
	}

}

package com.wesley.framework.dao.dbutils;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.dbutils.BasicRowProcessor;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.unitils.thirdparty.org.apache.commons.dbutils.DbUtils;

public class DBHelper<T> {
	private static final Logger logger = LoggerFactory
			.getLogger(DBHelper.class);

	private BasicDataSource pool;

	private Class<T> beanClass = null;

	public DBHelper(BasicDataSource pool) {
		super();
		this.pool = pool;
	}

	public DBHelper(BasicDataSource pool, Class<T> beanClass) {
		super();
		this.pool = pool;
		this.beanClass = beanClass;
	}

	/**
	 * 根据无参sql语句进行查询,并返回一个对象,用于单条记录的查询
	 * 
	 * @param sql
	 * @return Object
	 */
	public T query(String sql) {
		Connection conn = this.getPoolConnection();
		if (conn == null || beanClass == null)
			return null;
		QueryRunner run = new QueryRunner();
		ResultSetHandler<T> h = new BeanHandler<T>(beanClass);
		T result = null;
		try {
			result =   run.query(conn, sql, h);
		} catch (SQLException e) {
			logger.info("SQLException in [" + sql + "]");
			logger.error(e.getMessage());
		} finally {
			DbUtils.closeQuietly(conn);
		}
		return result;
	}

	/**
	 * 根据有参sql语句进行查询,并返回一个对象,用于单条记录的查询
	 * 
	 * @param sql
	 * @param args
	 * @return Object
	 */

	public T query(String sql, Object... args) {
		Connection conn = this.getPoolConnection();
		if (conn == null || beanClass == null)
			return null;
		QueryRunner run = new QueryRunner();
		ResultSetHandler<T> h = new BeanHandler<T>(beanClass);
		T result = null;
		try {
			result = (T) run.query(conn, sql, h, args);
		} catch (SQLException e) {
			logger.info("SQLException in [" + sql + "]");
			logger.error(e.getMessage());
		} finally {
			DbUtils.closeQuietly(conn);
		}
		return result;
	}

	/**
	 * 根据无参sql语句进行查询,并返回一个数据集,用于多条记录的查询
	 * 
	 * @param sql
	 * @return ArrayList
	 */
	public List<T> queryRecords(String sql) {
		Connection conn = this.getPoolConnection();
		if (conn == null || beanClass == null)
			return null;
		// ResultSetHandler<?> h = new BeanListHandler(beanClass);
		ResultSetHandler<List<T>> h = new BeanListHandler<T>(beanClass,
				new BasicRowProcessor(new StrategyBeanProcessor(
						new HumpMatcher())));
		QueryRunner run = new QueryRunner();
		List<T> result = null;
		try {
			result = run.query(conn, sql, h);
		} catch (SQLException e) {
			logger.info("SQLException in [" + sql + "]");
			logger.error(e.getMessage());
		} finally {
			DbUtils.closeQuietly(conn);
		}
		return result;
	}

	/**
	 * 根据有参sql语句进行查询,并返回一个数据集,用于多条记录的查询
	 * 
	 * @param sql
	 * @param args
	 * @return
	 */
	public List<T> queryRecords(String sql, Object... args) {
		Connection conn = this.getPoolConnection();
		if (conn == null || beanClass == null)
			return null;
		QueryRunner run = new QueryRunner();
		ResultSetHandler<List<T>> h = new BeanListHandler<T>(beanClass,
				new BasicRowProcessor(new StrategyBeanProcessor(
						new HumpMatcher())));
		List<T> result = null;

		try {
			result = run.query(conn, sql, h, args);
			System.out.println(result.size());
		} catch (SQLException e) {
			logger.info("SQLException in [" + sql + "]");
			logger.error(e.getMessage());
		} finally {
			DbUtils.closeQuietly(conn);
		}
		return result;
	}

	/**
	 * 根据无参sql语句进行数据更新,并返回更新后影响的记录数
	 * 
	 * @param sql
	 * @return int
	 */
	public int update(String sql) {
		Connection conn = this.getPoolConnection();
		if (conn == null)
			return 0;
		QueryRunner run = new QueryRunner();
		int result = 0;

		try {
			result = run.update(conn, sql);
		} catch (SQLException e) {
			logger.info("SQLException in [" + sql + "]");
			logger.error(e.getMessage());
		} finally {
			DbUtils.closeQuietly(conn);
		}
		return result;
	}

	/**
	 * 根据有参sql语句进行数据更新,并返回更新后影响的记录数
	 * 
	 * @param sql
	 * @param args
	 * @return int
	 */
	public int update(String sql, Object... args) {
		Connection conn = this.getPoolConnection();
		if (conn == null)
			return -1;

		QueryRunner run = new QueryRunner();
		int result = 0;

		try {
			result = run.update(conn, sql, args);
		} catch (SQLException e) {
			logger.info("SQLException in [" + sql + "]");
			logger.error(e.getMessage());
		} finally {
			DbUtils.closeQuietly(conn);
		}
		return result;
	}

	/**
	 * 设置存放查询结果的Bean类,每个Bean类对象对应一条查询的结果记录
	 * 
	 * @param beanClass
	 *            ,如User.class
	 */
	public void setBeanClass(Class<T> beanClass) {
		this.beanClass = beanClass;
	}

	public Connection getPoolConnection() {
		int x = 3;
		while (x > 0) {
			try {
				return pool.getConnection();
			} catch (SQLException e) {
				x--;
				logger.error(e.getMessage());
			}
		}
		return null;
	}

	public void dispose() {
		try {
			this.pool.close();
		} catch (SQLException e) {
			logger.error(e.getMessage());
		}
	}
}

<bean id="PrimaryGenerater" class="com.wesley.framework.dao.PrimaryGenerater"
		factory-method="newInstance">
		<constructor-arg index="0" ref="dataSource" />
		<constructor-arg index="1" >
			<map>
				<entry key="bsno">
					<value>select 'SP-' as prefix,'yyyyMMdd' as dataString,'000000' as
						startNumber union select null as prefix,null as dataString,null as
						startNumber from business
					</value>
				</entry>
			</map>
		</constructor-arg>
	</bean>
发表评论
用户名: 匿名