📄 hibernatebasedao.java
字号:
package cn.myapps.base.dao;
import java.util.Collection;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import cn.myapps.base.action.ParamsTable;
import cn.myapps.core.user.action.WebUser;
/**
* The base hibernate base dao.
*/
public class HibernateBaseDAO implements IBaseDAO {
private static Log log = LogFactory.getLog(HibernateBaseDAO.class);
private static SessionFactory sessionFactory;
public String _voClazzName;
// public static String dialect;
public HibernateBaseDAO(String valueObjectName) {
this._voClazzName = valueObjectName;
}
public HibernateBaseDAO() {
}
/**
* Return the session factory
*
* @return The session factory.
* @throws Exception
*/
public static SessionFactory getSessionFactory() throws Exception {
if (sessionFactory == null) {
Configuration cfg = new Configuration().configure();
/*
* Properties properties = cfg.getProperties(); dialect =
* properties.getProperty("hibernate.dialect");
*/
sessionFactory = cfg.buildSessionFactory();
}
return sessionFactory;
}
/**
* Get data Object
*
* @param hql
* @return object
* @see cn.myapps.base.dao.IBaseDAO#getData(java.lang.String)
*/
public Object getData(String hql) throws Exception {
Session session = currentSession();
Query query = session.createQuery(hql);
query.setFirstResult(0);
query.setFetchSize(1);
List list = query.list();
return (list.size() > 0) ? list.get(0) : null;
}
/**
* Get datas collection
*
* @param hql
* @return collection
* @see cn.myapps.base.dao.IBaseDAO#getDatas(java.lang.String)
*/
public Collection getDatas(String hql) throws Exception {
return getDatas(hql, 1, Integer.MAX_VALUE);
}
/**
* Get datas collection .
*
* @param hql
* @param params
* @return collection
* @see cn.myapps.base.dao.IBaseDAO#getDatas(java.lang.String,
* java.lang.Object)
*/
public Collection getDatas(String hql, ParamsTable params) throws Exception {
return getDatas(hql, params, 1, Integer.MAX_VALUE);
}
/**
* Get datas collection.
*
* @param hql
* @param params
* @param page
* @param lines
* @return collection Get datas collection
* @see cn.myapps.base.dao.IBaseDAO#getDatas(java.lang.String,
* java.lang.Object, int, int)
*/
public Collection getDatas(String hql, ParamsTable params, int page,
int lines) throws Exception {
// There is no detail syntax checking here, it may has some potential
// issue here.
HibernateSQLUtils sqlUtil = new HibernateSQLUtils();
String whereClause = sqlUtil.createWhere(_voClazzName, params);
if (whereClause != null && whereClause.trim().length() > 0) {
int p = hql.toLowerCase().indexOf(" where ");
hql = (p >= 0) ? hql.substring(0, p) + " where " + whereClause
+ " and " + hql.substring(p + 7) : hql + " where "
+ whereClause;
}
if (params != null) {
String application = (String) ((ParamsTable) params) // 根据instace 查询
.getParameter("application");
if (application != null && application.trim().length() > 0) {
if (hql.toLowerCase().indexOf(" where ") != -1) {
hql += " and applicationid='" + application + "'";
} else {
hql += " where applicationid='" + application + "'";
}
}
}
String orderBy = sqlUtil.createOrderBy(_voClazzName, params);
if (orderBy != null && orderBy.trim().length() > 0) {
int p = hql.toLowerCase().indexOf(" order by ");
hql = (p >= 0) ? hql.substring(0, p + 10) + orderBy + ", "
+ hql.substring(p + 10) : hql + " order by " + orderBy;
}
return getDatas(hql, page, lines);
}
/**
* Get TotalLines
*
* @param hql
* @return int
*
* @see cn.myapps.base.dao.IBaseDAO#getTotalLines(java.lang.String)
*/
public int getTotalLines(String hql) throws Exception {
Session session = currentSession();
Long amount = new Long(0);
int from = hql.toLowerCase().indexOf("from");
int order = hql.toLowerCase().indexOf("order by");
String newhql = (order > 0) ? "select count(*) "
+ hql.substring(from, order) : "select count(*) "
+ hql.substring(from);
Query query = session.createQuery(newhql);
if (!query.list().isEmpty())
amount = (Long) query.list().get(0);
else
return 0;
return amount.intValue();
}
/**
* @param hql
* @param page
* @param lines
* @return Collection Get datas collection.
* @see cn.myapps.base.dao.IBaseDAO#getDatas(java.lang.String, int, int)
*/
public Collection getDatas(String hql, int page, int lines)
throws Exception {
Session session = currentSession();
Query query = session.createQuery(hql);
query.setFirstResult((page - 1) * lines);
query.setMaxResults(lines);
return query.list();
}
/**
* @param hql
* @return DataPackage Get the datapackage.
*
* @see cn.myapps.base.dao.IBaseDAO#getDatapackage(java.lang.String)
*/
public DataPackage getDatapackage(String hql) throws Exception {
return getDatapackage(hql, 1, Integer.MAX_VALUE);
}
/**
* @param hql
* @param page
* @param lines
* @return dataPackape
*
* @see cn.myapps.base.dao.IBaseDAO#getDatapackage(java.lang.String, int,
* int)
*/
public DataPackage getDatapackage(String hql, int page, int lines)
throws Exception {
DataPackage result = new DataPackage();
result.rowCount = getTotalLines(hql);
result.pageNo = page;
result.linesPerPage = lines;
if (result.pageNo > result.getPageCount()) {
result.pageNo = 1;
page = 1;
}
result.datas = getDatas(hql, page, lines);
return result;
}
/**
*
* @see cn.myapps.base.dao.IBaseDAO#getDatapackage(java.lang.String,
* java.lang.Object)
*/
public DataPackage getDatapackage(String hql, ParamsTable params)
throws Exception {
// return getDatapackage(hql, params);
return getDatapackage(hql, params,1, Integer.MAX_VALUE);
}
/**
* Get the datapackage
*
* @param hql
* @param params
* Object
* @param page
* int
* @param lines
* int
* @return datapackage
*
* @see cn.myapps.base.dao.IBaseDAO#getDatapackage(java.lang.String,
* java.lang.Object, int, int)
*/
public DataPackage getDatapackage(String hql, ParamsTable params, int page,
int lines) throws Exception {
// There is no detail syntax checking here, it may has some potential
// issue here.
HibernateSQLUtils sqlUtil = new HibernateSQLUtils();
String whereClause = sqlUtil.createWhere(_voClazzName, params);
if (whereClause != null && whereClause.trim().length() > 0) {
int p = hql.toLowerCase().indexOf(" where ");
hql = (p >= 0) ? hql = hql.substring(0, p) + " where "
+ whereClause + " and " + hql.substring(p + 7) : hql
+ " where " + whereClause;
}
if (params != null) {
String application = (String) ((ParamsTable) params) // 根据instace 查询
.getParameter("application");
if (application != null && application.trim().length() > 0) {
if (hql.toLowerCase().indexOf(" where ") != -1) {
hql += " and applicationid='" + application + "'";
} else {
hql += " where applicationid='" + application + "'";
}
}
}
String orderBy = sqlUtil.createOrderBy(_voClazzName, params);
if (orderBy != null && orderBy.trim().length() > 0) {
int p = hql.toLowerCase().indexOf(" order by ");
hql = (p >= 0) ? hql.substring(0, p + 10) + orderBy + ", "
+ hql.substring(p + 10) : hql + " order by " + orderBy;
}
DataPackage result = new DataPackage();
result.rowCount = getTotalLines(hql);
result.pageNo = page;
result.linesPerPage = lines;
if (result.pageNo > result.getPageCount()) {
result.pageNo = 1;
page = 1;
}
result.datas = getDatas(hql, page, lines);
return result;
}
/**
* Execute the sql statement.
*
* @param hql
* The sql statement.
* @throws Exception
*/
protected void execHQL(String hql) throws Exception {
Session session = currentSession();
session.createQuery(hql).executeUpdate();
}
/**
*
* @see cn.myapps.base.dao.IBaseDAO#create(cn.myapps.base.dao.ValueObject,
* cn.myapps.core.user.action.WebUser)
*/
public void create(ValueObject vo, WebUser user) throws Exception {
Session session = currentSession();
session.save(vo);
}
/**
*
* @see cn.myapps.base.dao.IBaseDAO#create(cn.myapps.base.dao.ValueObject)
*/
public void create(ValueObject vo) throws Exception {
try {
Session session = currentSession();
session.save(vo);
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
*
* @see cn.myapps.base.dao.IBaseDAO#create(java.lang.Object)
*/
public void create(Object po) throws Exception {
Session session = currentSession();
session.save(po);
}
/**
*
* @see cn.myapps.base.dao.IBaseDAO#remove(java.lang.String)
*/
public void remove(String id) throws Exception {
Session session = currentSession();
ValueObject vo = find(id);
if (vo != null)
session.delete(vo);
}
/**
*
* @see cn.myapps.base.dao.IBaseDAO#update(cn.myapps.base.dao.ValueObject,
* cn.myapps.core.user.action.WebUser)
*/
public void update(ValueObject vo, WebUser user) throws Exception {
Session session = currentSession();
session.merge(vo);
}
/*
* (non-Javadoc)
*
* @see cn.myapps.base.dao.IBaseDAO#update(cn.myapps.base.dao.ValueObject)
*/
public void update(ValueObject vo) throws Exception {
Session session = currentSession();
session.merge(vo);
// session.saveOrUpdate(vo);
}
/**
* @see cn.myapps.base.dao.IBaseDAO#update(java.lang.Object)
*/
public void update(Object po) throws Exception {
Session session = currentSession();
session.merge(po);
}
/**
*
* @see cn.myapps.base.dao.IBaseDAO#find(java.lang.String)
*/
public ValueObject find(String id) throws Exception {
Session session = currentSession();
ValueObject rtn = null;
if (id != null && id.length() > 0) {
rtn = (ValueObject) session.get(Class.forName(_voClazzName), id);
if (rtn == null || rtn.getId() == null) {
String hql = "FROM " + _voClazzName + " WHERE id='" + id + "'";
Query query = session.createQuery(hql);
query.setFirstResult(0);
query.setMaxResults(1);
List result = query.list();
if (!result.isEmpty()) {
rtn = (ValueObject) result.get(0);
session.load(rtn, rtn.getId());
}
}
}
return rtn;
}
/**
*
*
* @see cn.myapps.base.dao.IBaseDAO#query(cn.myapps.base.action.ParamsTable)
*/
public DataPackage query(ParamsTable params) throws Exception {
String hql = "from " + _voClazzName;
String _currpage = params.getParameterAsString("_currpage");
String _pagelines = params.getParameterAsString("_pagelines");
int page = (_currpage != null && _currpage.length() > 0) ? Integer
.parseInt(_currpage) : 1;
int lines = (_pagelines != null && _pagelines.length() > 0) ? Integer
.parseInt(_pagelines) : Integer.MAX_VALUE;
return getDatapackage(hql, params, page, lines);
}
/**
* query datapackage
*
* @param params
* ParamsTable
* @param user
* WebUser
* @return datapackage
*/
public DataPackage query(ParamsTable params, WebUser user) throws Exception {
String hql = "from " + _voClazzName;
String _currpage = params.getParameterAsString("_currpage");
String _pagelines = params.getParameterAsString("_pagelines");
int page = (_currpage != null && _currpage.length() > 0) ? Integer
.parseInt(_currpage) : 1;
int lines = (_pagelines != null && _pagelines.length() > 0) ? Integer
.parseInt(_pagelines) : Integer.MAX_VALUE;
return getDatapackage(hql, params, page, lines);
}
public SessionFactory buildSessionFactory() throws Exception {
Configuration cfg = new Configuration().configure();
SessionFactory factory = cfg.buildSessionFactory();
return factory;
}
/**
*
* @see cn.myapps.base.dao.IBaseDAO#simpleQuery(cn.myapps.base.action.ParamsTable)
*/
public Collection simpleQuery(ParamsTable params) throws Exception {
String hql = "from " + _voClazzName;
return getDatas(hql, params);
}
/**
* Get the current session.
*
* @return The current session.
* @throws Exception
*/
protected static Session currentSession() throws Exception {
SessionSignal signal = PersistenceUtils.getSessionSignal();
Session s = signal.currentSession;
if (s == null) {
s = getSessionFactory().openSession();
log.debug("Opening new Session for this thread:" + s);
signal.currentSession = s;
} else {
log.debug("Session was existed:" + s);
}
return s;
}
/**
* Close the session.
*
* @throws Exception
*/
static void closeSession() throws Exception {
SessionSignal signal = PersistenceUtils.getSessionSignal();
Session s = signal.currentSession;
if (s != null && s.isOpen()) {
s.close();
signal.currentSession = null;
signal.currentTransaction = null;
// signal.sessionSignal = 0;
signal = null;
}
}
/**
* Open and begin the transcation
*
* @throws Exception
*/
static void beginTransaction() throws Exception {
SessionSignal signal = PersistenceUtils.getSessionSignal();
Transaction tx = signal.currentTransaction;
signal.transactionSignal++;
if (tx == null) {
tx = currentSession().beginTransaction();
log.debug("Starting new database transaction in this thread:" + tx);
signal.currentTransaction = tx;
} else {
log.debug("transaction was existed:" + tx);
}
}
/**
* Commit the transaction
*
* @throws Exception
*/
static void commitTransaction() throws Exception {
SessionSignal signal = PersistenceUtils.getSessionSignal();
Transaction tx = signal.currentTransaction;
signal.transactionSignal--;
try {
if (signal.transactionSignal <= 0) {
if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack()) {
log.debug("Commit database transaction of this thread.");
tx.commit();
signal.currentTransaction = null;
signal.transactionSignal = 0;
}
}
} catch (Exception ex) {
rollbackTransaction();
throw ex;
}
}
/**
* Roll back the transaction.
*
* @throws Exception
*/
static void rollbackTransaction() throws Exception {
SessionSignal signal = PersistenceUtils.getSessionSignal();
Transaction tx = signal.currentTransaction;
signal.currentTransaction = null;
signal.transactionSignal = 0;
if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack()) {
log.debug("Try to rollback database transaction of this thread.");
tx.rollback();
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -