- 浏览: 386745 次
- 性别:
- 来自: 上海
文章分类
- 全部博客 (213)
- 面试题目 (9)
- 设计模式 (7)
- Core Java (28)
- 杂记 (10)
- 代码模板 (6)
- 数据库 (6)
- oracle plsql (2)
- strut2 study note (1)
- Oracle Database 10g SQL开发指南学习笔记 (7)
- Unix.Shell编程(第三版) 学习笔记 (1)
- Servlet (1)
- Hibernate (1)
- 敏捷开发 (1)
- Linux (13)
- Velocity (1)
- webx (1)
- Svn (2)
- 页面html,css (2)
- English (4)
- Astah usage (1)
- UML与设计思考 (2)
- JavaScript (3)
- 读书 (4)
- 好的网址 (1)
- 网址 (0)
- JMS (1)
- 持续集成环境 (1)
- 生活 (1)
- Spring (3)
- Tomcat Server (1)
- MySQL (2)
- 算法与数据结构 (6)
- Oracle数据库 (1)
- 分布式计算 (1)
- Maven (1)
- XML (2)
- Perl (2)
- 游戏 (1)
最新评论
-
chen_yi_ping:
请问楼主,怎么测试?String filePath = arg ...
使用多线程模拟多用户并发访问一个或多个tomcat,测试性能 -
adam_zs:
好,谢谢分享。
ArrayDeque实现Stack的功能 -
zjfgf:
int.class==Integer.class 返回fals ...
Class study -
kimmking:
xslt太难写的。
在java中调用xls格式化xml
//通过读取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;
}
}
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;
}
}
发表评论
-
事实上
2011-08-10 18:13 0进程间通信 http://www.pin5i.com/show ... -
等待处理
2011-08-10 18:12 0类加载 tomcat优化 离线锁 concurrent包下的锁 ... -
gogogo
2011-08-04 17:54 0类加载 tomcat优化 离线锁 concurrent包下的锁 ... -
20110623
2011-06-23 13:48 900将数据库里的BLOB值查出来,生成文件: byte[] by ... -
20110622
2011-06-22 17:30 782删除文件或文件夹 public static void de ... -
杂记1
2011-06-12 11:07 8931.拦截器和过滤器的区别: 很多人都了解过滤器也听说过拦截器, ... -
杂记22
2011-06-10 18:00 866================= hibernate缓存 ... -
good site
2011-04-22 18:02 974Enterprise Job Scheduler http:/ ... -
20101025杂记
2010-10-25 15:18 9391.<property name="hiber ... -
Random类产生伪随机数
2010-10-09 18:50 1871Random类产生伪随机数,它的用法有点意识。 Random ... -
Today I will be master of my emotions
2010-09-20 18:55 1013Today I will be master of my em ... -
一个请求在Struts2框架中的处理大概分为以下几个步骤
2010-09-14 18:56 1580一个请求在Struts2框架中的处理大概分为以下几个步骤: ...
相关推荐
msysGit-fullinstall-1.7.6-preview20110708.exemsysGit-fullinstall-1.7.6-preview20110708.exemsysGit-fullinstall-1.7.6-preview20110708.exemsysGit-fullinstall-1.7.6-preview20110708.exemsysGit-fullinstall-...
在本文中,我们将深入探讨Git 1.7.6预览版20110708的特性,以及它如何与Android源码下载相结合,助力Android学习。 Git 1.7.6是Git的一个较早版本,发布于2011年,它包含了一系列改进和新功能。这个版本可能是为了...
《行业标准 地理信息公共服务平台地理实体与地名地址数据规范(送审稿)20110708》这份文档详细阐述了在地理信息公共服务领域中,如何规范地理实体和地名地址数据的采集、存储、管理和应用。这份标准对于保障地理...
git是一个分布式版本控制工具 Git --- The stupid content tracker, 傻瓜内容跟踪器。Linus 是这样给我们介绍 Git 的。 Git 是用于 Linux 内核开发的版本控制工具。与常用的版本控制工具 CVS, Subversion 等不同,...
测绘资料-行业标准 地理信息公共服务平台地理实体与地名地址数据规范(送审稿)20110708.pdf
Git,可以很方便的下载一些东西,如Android的源码等
### STM32中断优先级详解 #### 一、中断优先级概述 STM32(基于Cortex-M3内核)采用了一种独特的中断优先级管理机制,它涉及到两种类型的优先级:**抢占式优先级(Preemption Priority)**与**响应优先级...
"51758"可能是软件内部的版本号或代码,"zero"可能代表零错误或初始状态,而"20110708"则很可能是这个文件的创建日期,即2011年7月8日。安装或运行这个.exe文件,用户可以安装或升级到这个特定版本的“超级保护”...
首先,我们需要下载并安装Git客户端程序,例如Git-1.7.6-preview20110708.exe。安装模式选择缺省安装即可。 初始化用户信息 在使用Git客户端之前,我们需要初始化用户信息,这些信息将在以后的操作中使用。执行...
在提供的文件列表中,"Git-1.7.6-preview20110708.exe"是一个Git的安装程序,版本为1.7.6,这个版本相对较老,现在Git已经发展到了3.x版本,建议使用最新版本以获得更好的功能和安全性。 总的来说,Git作为一款强大...
设计开发思路:服务器: 每天凌晨2点(或其他时间,不需要程序设定,由任务计划完成)整理上一天新增的所有文件,写入到一个文件中,比如整理2011-07-08,那么就写入 20110708.txt文件中,整理完毕关闭程序。...