日期:2014-05-18 浏览次数:20980 次
/**
* 传入一个Object ,如User,将保存user相关的信息.
* @param obj
* @return 保存对象的id
* @throws HibernateException 数据库操作异常
*/
static Serializable create(Object obj)
{
Session session = null;
try
{
//如果传入的对象为null,或者不是合法的DTO。
if (null == obj || !isValidClass(obj.getClass()))
{
throw new IllegalArgumentException(
"argument is null,or class is invalid!");
}
else
{
// 开启连接
session = HibernateUtil.currentSession();
// 开启事务
Transaction tx = session.beginTransaction();
Serializable id = session.save(obj);
tx.commit();
return id;
}
}
catch (HibernateException ex)
{
LOG.error("create failed, obj=" + obj.toString(), ex);
throw ex;
}
finally
{
HibernateUtil.closeSession(session);
}
}
/**
* 执行sql语句
*/
static void updateBySQL(String sql) throws SQLException
{
if (null == sql)
{
return;
}
Session session = null;
Connection conn = null;
Statement ste = null;
try
{
session = HibernateUtil.currentSession();
Transaction tx = session.beginTransaction();
conn = session.connection();
ste = conn.createStatement();
ste.executeUpdate(sql);
tx.commit();
}
catch (SQLException ex)
{
LOG.error("updateBySQL failed, sql=" + sql, ex);
throw ex;
}
catch (HibernateException ex)
{
LOG.error("updateBySQL failed, sql=" + sql, ex);
throw ex;
}
finally
{
if (ste != null)
{
ste.close();
}
if (conn != null)
{
conn.close();
}
HibernateUtil.closeSession(session);
}
}
------解决方案--------------------
Hibernate支持原生SQL
getSession().createSQLQuery(sql)
------解决方案--------------------