20110708

//通过读取classpath下的abc.properties,来获取配置参数。
public class GlobalConfig {
private static final String CONFIG_FILE_NAME = "abc.properties";
private static final String KEY_PATH = "appconfig.path";
static {
loadGlobalConfig();
}

/**
* load default values from classpath:abc.properties
*/
private static void loadGlobalConfig() {

try {
props.load(GlobalConfig.class.getClassLoader().getResourceAsStream(CONFIG_FILE_NAME));
} catch (Exception ex) {
ex.printStackTrace();
}
}

public static String getPartiAppConfigPath(){
return props.getProperty(KEY_PATH);
}
}
=====
Use Enum Type:
public class People {
public enum PeopleType {
Man, Woman, Unknown;

public static PeopleType getGender(char s) {
switch (s) {
case 'M':
return Man;
case 'F':
return Woman;
}
return Unknown;
}
}

public static void doLoad() throws Exception {
System.out.println(People.PeopleType.getGender('M'));
}
}
=====
/*For web project,read the bean from spring's container, these beans in container is initialized when reading web.xml file, the context-param assign the other context(spring.xml)*/
/*WEB-INF
--spring-servlet.xml
--web.xml

*/
<web-app...>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-servlet.xml</param-value>
</context-param>
</web-app>
public class DownloadConfig extends HttpServlet {
private JdbcTemplate jdbcTemplate;
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}

protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {

}
public void init() throws ServletException {
super.init();
if (jdbcTemplate == null) {
jdbcTemplate = (JdbcTemplate) WebApplicationContextUtils
.getRequiredWebApplicationContext(getServletContext())
.getBean("jdbcTemplate");
}
}
}
=====
Save the inputStream to Blob field in DB.
use "SELECT WHERE ..FOR UPDATE"
//1.有where条件时,锁定条件中指定的数据行(行级封锁);
//2.无where条件时,锁定表A(表级封锁)。
http://blog.csdn.net/annicybc/archive/2007/04/30/1592737.aspx
import org.springframework.jdbc.core.support.JdbcDaoSupport;
public class TestDAO extends JdbcDaoSupport implements TestDAOInterface {

private void updateContent(ClassA classA) {
Connection con = null;
try {
con = getJdbcTemplate().getDataSource().getConnection();

String sql = "SELECT CONTENT FROM A WHERE CODE=? FOR UPDATE";
String sql2 = "UPDATE A SET CONTENT=EMPTY_BLOB(), UPDATED_TIME = ? WHERE CODE=?";

PreparedStatement pst = con.prepareStatement(sql);
PreparedStatement pst2 = con.prepareStatement(sql2);
pst.setString(1, classA.getCode());
pst2.setTimestamp(1, new Timestamp(System.currentTimeMillis()));
pst2.setString(2, classA.getCode());
pst2.execute();
ResultSet rs = pst.executeQuery();
if (rs.next()) {
Blob mapBlob = rs.getBlob("CONTENT");
OutputStream blobOutputStream = mapBlob.setBinaryStream(1);
InputStream sampleFileStream = classA.getIs();
byte[] buffer = new byte[10 * 1024];
int nread = 0;
// Number of bytes read
while ((nread = sampleFileStream.read(buffer)) != -1) {
// Read from file
blobOutputStream.write(buffer, 0, nread);
// Write to Blob Close both streams
}
sampleFileStream.close();
blobOutputStream.close();
}
con.commit();
} catch (Exception ee) {
try {
con.rollback();
} catch (SQLException e) {
logger.error(e.getStackTrace());
}
logger.info(ee);
} finally {
try {
if (con != null) {
con.close();
}
} catch (SQLException e) {
logger.error(e.getStackTrace());
}
}
}
}
public class ClassA {
private String code;
private InputStream is;
//get and set method...
}
=====
use spring TransactionTemplate:
spring.cfg.xml file:
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>

<bean id="txnTemplate"
class="org.springframework.transaction.support.TransactionTemplate">
<property name="transactionManager" ref="txManager"/>
</bean>
usage in class:
import org.springframework.jdbc.datasource.DataSourceUtils;
public class Test extends HttpServlet {
private TransactionTemplate txnTemplate;
public void init() throws ServletException {
if (txnTemplate == null) {
txnTemplate = (TransactionTemplate) WebApplicationContextUtils
.getRequiredWebApplicationContext(getServletContext())
.getBean("txnTemplate");
}
}

protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
//...
Object ret = txnTemplate.execute(new TransactionCallback() {
//if occur some exception in doInTransaction method, the operation in db will rollback.
public Object doInTransaction(TransactionStatus arg0) {
storeRawRecord(parameter1, parameter2)//进行第一步数据库操作
storeRecord(parameter1, parameter2);//database operation
return true;
}

});

if (ret != null && ret == Boolean.TRUE) {//如果总的数据库操作成功,做logger。
logger.info("Success! ");
} else {
throw new Exception("Fail to insert record into tables.");
}
//...
}

private void storeRecord(parameter1, parameter2){
if(满足业务逻辑,例如,没有重复的记录){
进行插入数据操作;
}else{
//进行rollback(),将第一次对数据库的操作storeRawRecord擦除
DataSourceUtils.getConnection(jdbcTemplate.getDataSource()).rollback();
}
}
}
source code:
public class TransactionTemplate extends DefaultTransactionDefinition
implements TransactionOperations, InitializingBean {


public <T> T execute(TransactionCallback<T> action) throws TransactionException {
if (this.transactionManager instanceof CallbackPreferringPlatformTransactionManager) {
return ((CallbackPreferringPlatformTransactionManager) this.transactionManager).execute(this, action);
}
else {
TransactionStatus status = this.transactionManager.getTransaction(this);
T result = null;
try {
result = action.doInTransaction(status);
}
catch (RuntimeException ex) {
// Transactional code threw application exception -> rollback
rollbackOnException(status, ex);
throw ex;
}
catch (Error err) {
// Transactional code threw error -> rollback
rollbackOnException(status, err);
throw err;
}
this.transactionManager.commit(status);
return result;
}
}
}
=====
import org.springframework.orm.hibernate3.HibernateTemplate;
public class Abc{
private HibernateTemplate hibernateTemplate;
//hibernateTemplate.executeFind方法会在当前session中进行数据库操作。
public List find(final OnePojo onePojo) {
List result = hibernateTemplate
.executeFind(new HibernateCallback() {
public Object doInHibernate(Session session)
throws HibernateException, SQLException {
return session.createQuery(
"sql query ... where onePojo.field=...")
.list();
}
});
return result;
}



API:
org.hibernate.Session:
It is not intended that implementors be threadsafe. Instead each thread/transaction should obtain its own instance from a SessionFactory.(me:这并不意味着session的实现是线程安全的。而是每个线程/事务应该从sessionFactory中获得自己的实例。这是事务和线程是绑定的,这样每个线程都操作自己从sessionFactory中得到的实例,不会产生多个线程操作同一个实例,因此线程的安全问题也就解决了。)
class HibernateTemplate
public List executeFind(HibernateCallback action)
throws DataAccessException

Description copied from interface: HibernateOperations
Execute the specified action assuming that the result object is a List.

This is a convenience method for executing Hibernate find calls or queries within an action.

Specified by:
executeFind in interface HibernateOperations

Parameters:
action - calback object that specifies the Hibernate action
Returns:
a List result returned by the action, or null


public interface HibernateCallback

Callback interface for Hibernate code. To be used with HibernateTemplate's execution methods, often as anonymous classes within a method implementation. A typical implementation will call Session.load/find/update to perform some operations on persistent objects. It can also perform direct JDBC operations via Hibernate's Session.connection(), operating on a JDBC Connection.

Note that Hibernate works on unmodified plain Java objects, performing dirty detection via copies made at load time. Returned objects can thus be used outside of an active Hibernate Session without any hassle, e.g. for display in a web GUI. Reassociating such instances with a new Session, e.g. for updates when coming back from the GUI, is straightforward, as the instance has kept its identity. You should care to reassociate them as early as possible though, to avoid having already loaded a version from the database in the same Session.(me:注意hibernate工作在不可修改引用的java对象上,目前认为是final类型的java对象,通过在加载时的副本进行脏数据的检测。从数据库返回的对象因此可以在hibernate的session外使用,而不产生错误,例如,在网页图形界面中展现。使用新的session重新关联这些实例,例如,当从图形界面返回数据到数据库进行更新操作,很明确的,因为实例都保持它的唯一性。然而,你必须注意重新关联他们越早越好,来避免已经通过相同的session从数据库里取得这些数据的一个版本了。会根据最新的版本将数据返回到数据库。)


source code:
public class HibernateTemplate extends HibernateAccessor implements HibernateOperations {

public List executeFind(HibernateCallback<?> action) throws DataAccessException {
Object result = doExecute(action, false, false);
if (result != null && !(result instanceof List)) {
throw new InvalidDataAccessApiUsageException(
"Result object returned from HibernateCallback isn't a List: [" + result + "]");
}
return (List) result;
}


/**
* Execute the action specified by the given action object within a Session.
* @param action callback object that specifies the Hibernate action
* @param enforceNewSession whether to enforce a new Session for this template
* even if there is a pre-bound transactional Session
* @param enforceNativeSession whether to enforce exposure of the native
* Hibernate Session to callback code
* @return a result object returned by the action, or <code>null</code>
* @throws org.springframework.dao.DataAccessException in case of Hibernate errors
*/
protected <T> T doExecute(HibernateCallback<T> action, boolean enforceNewSession, boolean enforceNativeSession)
throws DataAccessException {
Assert.notNull(action, "Callback object must not be null");

Session session = (enforceNewSession ?
SessionFactoryUtils.getNewSession(getSessionFactory(), getEntityInterceptor()) : getSession());
boolean existingTransaction = (!enforceNewSession &&
(!isAllowCreate() || SessionFactoryUtils.isSessionTransactional(session, getSessionFactory())));
if (existingTransaction) {
logger.debug("Found thread-bound Session for HibernateTemplate");
}

FlushMode previousFlushMode = null;
try {
previousFlushMode = applyFlushMode(session, existingTransaction);
enableFilters(session);
Session sessionToExpose =
(enforceNativeSession || isExposeNativeSession() ? session : createSessionProxy(session));
T result = action.doInHibernate(sessionToExpose);
flushIfNecessary(session, existingTransaction);
return result;
}
catch (HibernateException ex) {
throw convertHibernateAccessException(ex);
}
catch (SQLException ex) {
throw convertJdbcAccessException(ex);
}
catch (RuntimeException ex) {
// Callback code threw application exception...
throw ex;
}
finally {
if (existingTransaction) {
logger.debug("Not closing pre-bound Hibernate Session after HibernateTemplate");
disableFilters(session);
if (previousFlushMode != null) {
session.setFlushMode(previousFlushMode);
}
}
else {
// Never use deferred close for an explicitly new Session.
if (isAlwaysUseNewSession()) {
SessionFactoryUtils.closeSession(session);
}
else {
SessionFactoryUtils.closeSessionOrRegisterDeferredClose(session, getSessionFactory());
}
}
}
}
}
====
public class DateHelper
{
private static SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyyMMdd");
private static SimpleDateFormat dateFormat3 = new SimpleDateFormat("ddMMMyyyy",Locale.ENGLISH);

public static final String dateToFormat(String format,Date date){

DateFormat df = new SimpleDateFormat(format);
return df.format(date);
}

public static String mailSubjectDate(String yyyyMMdd) {
String date = null;
try
{
date = dateFormat3.format(dateFormat2.parse(yyyyMMdd));
} catch (ParseException e)
{
date = yyyyMMdd;
}

return date;
}

public static boolean is_yyyyMMdd(String date){
try{
dateFormat2.parse(date);
} catch (ParseException e){
return false;
}
return true;
}
}
/* Date formats are not synchronized.
* It is recommended to create separate format instances for each thread.
* If multiple threads access a format concurrently, it must be synchronized
* externally.*/
so the right code is:
public class DateHelper
{
public static final String dateToFormat(String format,Date date){
DateFormat df = new SimpleDateFormat(format);
return df.format(date);
}

public static String mailSubjectDate(String yyyyMMdd) {
SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyyMMdd");
SimpleDateFormat dateFormat3 = new SimpleDateFormat("ddMMMyyyy",Locale.ENGLISH);
String date = null;
try
{
date = dateFormat3.format(dateFormat2.parse(yyyyMMdd));
} catch (ParseException e)
{
date = yyyyMMdd;
}

return date;
}

public static boolean is_yyyyMMdd(String date){
SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyyMMdd");
try{
dateFormat2.parse(date);
} catch (ParseException e){
return false;
}
return true;
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值