封装的新方法,基于Hibernate,可以快速执行sql
我封装了两个只要写好sql就可以执行的方法,
一个是获取所有语句,另一个是支持分页,做分页时可以只写一个sql就可以了,不用像以前要写两个sql,可以提高效率。
Hibernate , Minidao,的总结
添加Hql执行count(*)值方法
话不多说,直接上代码。
框架的查询,分页查询代码不好用,非常不好用
目录
后端JAVA
执行代码
前端代码
为Hibernate读取sql文件
public static String getPathByClass(Class entityClass,String sqlName) {
URL path = entityClass.getResource("");
File file = new File(path.getPath()).getParentFile();
file = new File(file.getPath()+File.separator+"dao"+File.separator+sqlName);
try {
return(IOUtils.toString(new FileInputStream(file)));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
System.out.println(getPathByClass(FieldEitity.class,"TestDao_getAllFieldFromTable.sql"));
}
public static void main4(String[] args) {
URL path = DccInternalFileController.class.getResource("/");
System.out.println(path.getPath());
path = DccInternalFileController.class.getResource("");
System.out.println(path.getPath());
File file = new File(path.getPath());
System.out.println(file.getPath());
file = file.getParentFile();
System.out.println(file.getPath());
file = new File(file.getPath()+File.separator+"dao"+File.separator+"DccInternalDao_getDataPageBysepcNo.sql");
System.out.println(file.getPath());
try {
System.out.println(IOUtils.toString(new FileInputStream(file)));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
String hql = "select distinct printBy from CircleRecoveryconfirmEntity where nodeid='001' and needrecycle='Y' and specNo in (:specNoList)";
Query queryObject = getSession().createQuery(hql);
queryObject.setParameterList("specNoList", specnoArr);
List stringlist = queryObject.list();
/**
*
*/
package com.dcc.common.service.impl;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;
import org.hibernate.Cache;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.web.system.pojo.base.TSDepart;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.jeecgframework.web.system.service.SystemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import com.circle.core.util.StringUtility;
import com.dcc.common.entity.DccBaseUserEntity;
import com.dcc.common.service.CircleCommonDaoService;
import com.dcc.common.service.RecordExceptionService;
/**
* create at 2022-04-27
*
* @version 0.0.8
* @author tianming.fan
*
*/
@Service("CircleCommonDaoService")
public class CircleCommonDaoServiceImpl implements CircleCommonDaoService {
/*
* @Autowired private CommonService commonService;
*/
@Autowired
private SystemService systemService;
@Autowired
private RecordExceptionService recordExceptionService;
@SuppressWarnings("unchecked")
@Override
public List findListbySql(String sql, Class entityClass, Object... param) {
Session session = systemService.getSession();
if (!session.isOpen()||!session.isConnected()) {
recordExceptionService.recordPrintErrMsgByLogLevel("Hibernate Session 未开启", Globals.LOG_LEAVEL_INFO);
session = session.getSessionFactory().openSession();
}
if (!session.isOpen()||!session.isConnected()) {
recordExceptionService.recordPrintErrMsgByLogLevel("Hibernate Session 未连接", Globals.LOG_LEAVEL_INFO);
session = systemService.getNewSession();// 重新创建Session
}
// getCurrentSession () 使用当前的session
// openSession() 重新建立一个新的session
SQLQuery sqlQuery = session.createSQLQuery(sql);
sqlQuery.addEntity(entityClass);
if (param != null && param.length > 0) {
for (int i = 0; i < param.length; i++) {
sqlQuery.setParameter(i, param[i]);
}
}
return sqlQuery.list();
}
@Override
public List findListBySqlMap(String sql, Class entityClass, Map stringMap,
Map arrMap) {
SQLQuery sqlQuery = systemService.getSession().createSQLQuery(sql);
sqlQuery.addEntity(entityClass);
for (Map.Entry entry : stringMap.entrySet()) {
sqlQuery.setParameter(entry.getKey(), entry.getValue());
}
for (Map.Entry entry : arrMap.entrySet()) {
sqlQuery.setParameterList(entry.getKey(), entry.getValue());
}
return sqlQuery.list();
}
/**
* startRow: 开始行数 rows: 每页行数
*/
@SuppressWarnings("unchecked")
@Override
public List findPageListBySql(String sql, Class entityClass, int startRow, int rows, Object... param) {
SQLQuery sqlQuery = systemService.getSession().createSQLQuery(sql);
sqlQuery.addEntity(entityClass);
sqlQuery.setFirstResult(startRow);
sqlQuery.setMaxResults(rows);
if (param != null && param.length > 0) {
for (int i = 0; i < param.length; i++) {
sqlQuery.setParameter(i, param[i]);
}
}
return sqlQuery.list();
}
@Override
public List findPageListBySqlPage(String sql, Class entityClass, int page, int rows, Object... param) {
/*
* 这是sql的分页方式,第几行到第几行 int pageInt = page; int rowsInt = rows; int startRow =
* (pageInt-1)*rowsInt+1; int endRow = pageInt*rowsInt;
*/
int pageInt = page;
int rowsInt = rows;
int startRow = (pageInt - 1) * rowsInt + 1 - 1;// hibernate的数据行数是从零开始的,需要减一
return findPageListBySql(sql, entityClass, startRow, rows, param);
}
@Override
public List findHqlMap(String hql, Map stringMap, Map arrMap) {
Query queryObject = systemService.getSession().createQuery(hql);
for (Map.Entry entry : stringMap.entrySet()) {
queryObject.setParameter(entry.getKey(), entry.getValue());
}
for (Map.Entry entry : arrMap.entrySet()) {
queryObject.setParameterList(entry.getKey(), entry.getValue());
}
return queryObject.list();
}
/**
* 通过hql 查询语句查找对象
*
* startRow:开始行数 rows:每页行数
*
* @return
*/
@SuppressWarnings("unchecked")
@Override
public List findPageListByHql(final String hql, int startRow, int rows, Object... param) {
Query queryObject = systemService.getSession().createQuery(hql);
queryObject.setFirstResult(startRow);
queryObject.setMaxResults(rows);
if (param != null && param.length > 0) {
for (int i = 0; i < param.length; i++) {
queryObject.setParameter(i, param[i]);
}
}
List list = queryObject.list();
return list;
}
/**
* 使用hibernate框架,直接执行hql语句,支持分页
*
* @param hql
* @param page
* 页数
* @param rows
* 一页的行数
* @param param
* hql参数
* @return
*/
@SuppressWarnings("unchecked")
@Override
public List findPageListByHqlPage(final String hql, int page, int rows, Object... param) {
int pageInt = page;
int rowsInt = rows;
int startRow = (pageInt - 1) * rowsInt + 1 - 1;// hibernate的数据行数是从零开始的,需要减一
// int endRow = pageInt*rowsInt;
return findPageListByHql(hql, startRow, rows, param);
}
// ******************************************************************
/**
* 根据属性名和属性值查询. 有排序
*
* @param
* @param entityClass
* @param propertyName
* @param value
* @param propertySort
* @param isAsc
* @return
*/
@SuppressWarnings("unchecked")
@Override
public List findByPropertyisOrder(Class entityClass, String propertyName, Object value, boolean isAsc,
String propertySort) {
Assert.hasText(propertyName);
Criteria criteria = createCriteria(entityClass, isAsc, propertySort, Restrictions.eq(propertyName, value));
return criteria.list();
}
/**
* 创建Criteria对象,有排序功能。
*
* @param
* @param entityClass
* @param propertySort
* @param isAsc
* @param criterions
* @return
*/
private Criteria createCriteria(Class entityClass, boolean isAsc, String propertySort,
Criterion... criterions) {
Criteria criteria = createCriteria(entityClass, criterions);
if (isAsc) {
criteria.addOrder(Order.asc(propertySort));
} else {
criteria.addOrder(Order.desc(propertySort));
}
return criteria;
}
/**
* 创建Criteria对象带属性比较
*
* @param
* @param entityClass
* @param criterions
* @return
*/
@SuppressWarnings("finally")
private Criteria createCriteria(Class entityClass, Criterion... criterions) {
Criteria criteria = null;
try {
Session session = systemService.getSession();
criteria = session.createCriteria(entityClass);
for (Criterion c : criterions) {
criteria.add(c);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
return criteria;
}
}
// -------------------------------------------------
@Override
public TSUser getUserByUserName(String username) {
List list = systemService.findByProperty(TSUser.class, "userName", username);
if (list.size() > 0) {
String queryDept = "from TSDepart where id = ?";
List departs = systemService.findHql(queryDept, list.get(0).getDepartid());
TSUser baseUser = list.get(0);
baseUser.setDeptname(departs.get(0).getDepartname());
return baseUser;
} else {
return getUserByEmpNo(username);
}
}
private TSUser getUserByEmpNo(String empno) {
List list = systemService.findByProperty(TSUser.class, "empno", empno);
if (list.size() > 0) {
String queryDept = "from TSDepart where id = ?";
List departs = systemService.findHql(queryDept, list.get(0).getDepartid());
TSUser baseUser = list.get(0);
baseUser.setDeptname(departs.get(0).getDepartname());
return baseUser;
} else {
return null;
}
}
// ============================================
// insert hql 未启用
private void insertHqlSingleService(String tableName, Map fieldMap) throws Exception {
String hql = "insert into #{tableName} (#{field}) values(#{values})";
hql = StringUtility.replace(hql, "#{tableName}", tableName);
StringBuilder fieldHqlBuilder = new StringBuilder();
for (String key : fieldMap.keySet()) {
fieldHqlBuilder = StringUtility.builderAppend(fieldHqlBuilder, key, ",");
}
fieldHqlBuilder.deleteCharAt(fieldHqlBuilder.length() - 1);
StringBuilder valuesHqlBuilder = new StringBuilder();
for (String key : fieldMap.keySet()) {
valuesHqlBuilder = StringUtility.builderAppend(valuesHqlBuilder, "'", fieldMap.get(key), "',");
}
valuesHqlBuilder.deleteCharAt(valuesHqlBuilder.length() - 1);
hql = StringUtility.replace(hql, "#{field}", fieldHqlBuilder.toString(), "#{values}",
valuesHqlBuilder.toString());
recordExceptionService.recordPrintErrMsg("insertHqlSingleService hql:" + hql);
updateHql(hql);
}
// ---------------------------------
// insert sql
@Override
public void insertSqlSingleService(String tableName, Map fieldMap) throws Exception {
String sql = "insert into #{tableName} (#{field}) values(#{values})";
sql = StringUtility.replace(sql, "#{tableName}", tableName);
StringBuilder fieldSqlBuilder = new StringBuilder();
for (String key : fieldMap.keySet()) {
fieldSqlBuilder = StringUtility.builderAppend(fieldSqlBuilder, key, ",");
}
fieldSqlBuilder.deleteCharAt(fieldSqlBuilder.length() - 1);
StringBuilder valuesSqlBuilder = new StringBuilder();
for (String key : fieldMap.keySet()) {
valuesSqlBuilder = StringUtility.builderAppend(valuesSqlBuilder, "'", fieldMap.get(key), "',");
}
valuesSqlBuilder.deleteCharAt(valuesSqlBuilder.length() - 1);
sql = StringUtility.replace(sql, "#{field}", fieldSqlBuilder.toString(), "#{values}",
valuesSqlBuilder.toString());
recordExceptionService.recordPrintErrMsg("insertSqlSingleService sql:" + sql);
systemService.executeSql(sql);
}
// ------------------------------------
// update语句自动生成,和执行的方法
// 传入表(String),字段和值(HashMap),传入条件(HashMap)
/**
* 自动生成update Sql语句
*
* @param tableName
* @param fieldMap
* @param condiMap
* @param sqlExtend
* @throws Exception
*/
@Override
public void updateSqlEqualsService(String tableName, Map fieldMap, Map condiMap,
String sqlExtend) throws Exception {
String sql = "update #{tableName} set #{field} where 1=1 #{condition}";
sql = StringUtility.replace(sql, "#{tableName}", tableName);
StringBuilder fieldSqlBuilder = new StringBuilder();
for (String key : fieldMap.keySet()) {
fieldSqlBuilder = StringUtility.builderAppend(fieldSqlBuilder, key, "='", fieldMap.get(key), "',");
}
fieldSqlBuilder.deleteCharAt(fieldSqlBuilder.length() - 1);
StringBuilder condiSqlBuilder = new StringBuilder();
for (String key : condiMap.keySet()) {
condiSqlBuilder = StringUtility.builderAppend(condiSqlBuilder, "and ", key, "='", condiMap.get(key), "'");
}
condiSqlBuilder.append(sqlExtend);
sql = StringUtility.replace(sql, "#{field}", fieldSqlBuilder.toString(), "#{condition}",
condiSqlBuilder.toString());
recordExceptionService.recordPrintErrMsg("updateSqlEqualsService sql:" + sql);
systemService.executeSql(sql);
}
@Override
public void updateHqlEqualsService(String className, Map fieldMap, Map condiMap,
String sqlExtend) throws Exception {
String hql = "update #{className} set #{field} where 1=1 #{condition}";
hql = StringUtility.replace(hql, "#{className}", className);
StringBuilder fieldSqlBuilder = new StringBuilder();
for (String key : fieldMap.keySet()) {
fieldSqlBuilder = StringUtility.builderAppend(fieldSqlBuilder, key, "='", fieldMap.get(key), "',");
}
fieldSqlBuilder.deleteCharAt(fieldSqlBuilder.length() - 1);
StringBuilder condiSqlBuilder = new StringBuilder();
for (String key : condiMap.keySet()) {
condiSqlBuilder = StringUtility.builderAppend(condiSqlBuilder, "and ", key, "='", condiMap.get(key), "'");
}
condiSqlBuilder.append(sqlExtend);
hql = StringUtility.replace(hql, "#{field}", fieldSqlBuilder.toString(), "#{condition}",
condiSqlBuilder.toString());
recordExceptionService.recordPrintErrMsg("updateHqlEqualsService hql:" + hql);
updateHql(hql);
}
/**
* 直接执行Hql语句
*
* @param hql
* @return
* @throws Exception
*/
@Override
public int updateHql(String hql) throws Exception {
Query queryObject = systemService.getSession().createQuery(hql);
int ret = queryObject.executeUpdate();// insert update都可以执行
return ret;
}
@Override
public int updateHql(String hql, Object... param) throws Exception {
Query queryObject = systemService.getSession().createQuery(hql);
if (param != null && param.length > 0) {
for (int i = 0; i < param.length; i++) {
queryObject.setParameter(i, param[i]);
}
}
int ret = queryObject.executeUpdate();// insert update都可以执行
return ret;
}/**/
// ----------------------------------
/*
* 返回数组
[
[
"F2-2-003",
"测试运维工具",
"1",
"F2-2-003-F001-00",
"关于2017年姑苏区微信开发深度解析培训班的通知.docx"
],
[
"F2-2-003",
"测试运维工具",
"1",
"F2-2-003-F002-00",
"赛科.xlsx"
],
[
"F2-2-003",
"测试运维工具",
"1",
"F2-2-003-F007-00",
"QA-F-115 Fab?Weekly?Report?Format.pptx"
]
]
*
* */
@SuppressWarnings("unchecked")
@Override
public List findListbySql(String sql, Object... param) {
Session session = systemService.getSession();
if (!session.isOpen()||!session.isConnected()) {
recordExceptionService.recordPrintErrMsgByLogLevel("Hibernate Session 未开启", Globals.LOG_LEAVEL_INFO);
session = session.getSessionFactory().openSession();
}
if (!session.isOpen()||!session.isConnected()) {
recordExceptionService.recordPrintErrMsgByLogLevel("Hibernate Session 未连接", Globals.LOG_LEAVEL_INFO);
session = systemService.getNewSession();// 重新创建Session
}
// getCurrentSession () 使用当前的session
// openSession() 重新建立一个新的session
SQLQuery sqlQuery = session.createSQLQuery(sql);
if (param != null && param.length > 0) {
for (int i = 0; i < param.length; i++) {
sqlQuery.setParameter(i, param[i]);
}
}
return sqlQuery.list();
}
}
/**
*
*/
package com.dcc.common.service;
import java.util.List;
/**
* @author tianming.fan
*
*/
public interface CircleCommonDaoService {
/**
* 使用hibernate框架,直接执行sql语句
*
* @param sql
* @param entityClass
* @param param sql参数
* @return
*/
public List findListbySql(String sql, Class entityClass, Object... param);
/**
* 使用hibernate框架,直接执行sql语句,支持分页
*
* @param sql
* @param entityClass
* @param startRow 第一条数据行数
* @param rows 每页行数
* @param param sql参数
* @return
*/
public List findPageListBySql(String sql,Class entityClass,int startRow,int rows, Object... param);
/**
* 使用hibernate框架,直接执行sql语句,支持分页,传入页数和行数
*
* @param sql
* @param entityClass
* @param page 页数
* @param rows 一页的行数
* @param param sql参数
* @return
*/
public List findPageListBySqlPage(String sql, Class entityClass, int page, int rows, Object... param);
/**
* 使用hibernate框架,直接执行hql语句
*
* @param hql
* @param startRow 第一条数据行数
* @param rows 每页行数
* @param param sql参数
* @return
*/
public List findPageListByHql(final String hql, int startRow, int rows, Object... param);
/**
* 使用hibernate框架,直接执行hql语句,支持分页
*
* @param hql
* @param page 页数
* @param rows 一页的行数
* @param param sql参数
* @return
*/
public List findPageListByHqlPage(final String hql, int page, int rows, Object... param);
/**
* 通过属性称获取实体带排序
*
* @param entityClass
* @param propertyName
* @param value
* @param isAsc
* @param propertySort 排序的字段
* @return
*/
public List findByPropertyisOrder(Class entityClass,
String propertyName, Object value, boolean isAsc,String propertySort);
}
获取Count数量,框架
Long total=systemService.getCountForJdbc("select count(*) from t_s_function where functionlevel=0");
hql 取到 count(*)的值
@SuppressWarnings("unchecked")
@Override
public int getAllAmount(String saveCell) {
String hql="select count(*) from Detail where saveCell=? and status=?";
Object[] params={saveCell,true};
List list=
this.getHibernateTemplate().find(hql, params);
/*
* 这里在Hibernate2.0之前版本list.get(0)返回的是Integer类型.
但是在Hibernate3.0以后版本list.get(0)返回的是Long类型.
* */
Number num =list.get(0);
int amount=num.intValue();
return amount;
}
public Integer executeSql(String sql, List
//-----
String sql = "update super_query_history set history_name=" + "'" + name + "' where user_id=" + "'" + userId + "' and history_name=" + "'" + nodeName + "'";
int updateByName = systemService.updateBySqlString(sql);
String sql = "delete from super_query_history where history_name=" + "'" + name + "' and user_id=" + "'" + userId + "'";
int deletebyName = systemService.updateBySqlString(sql);
/**
* 通过sql更新记录
*
* @param
* @param query
* @return
*/
public int updateBySqlString(final String query) {
Query querys = getSession().createSQLQuery(query);
return querys.executeUpdate();
}
//--------- 亲测不好用,需要自己写别名字段名
List list = systemService.findObjForJdbc(sql1, curPageNO, pageSize, CircleChaptertempGroupEntity.class);
/**
* 亲测不好用,需要自己写别名字段名
*
* 使用指定的检索标准检索数据并分页返回数据
*
* @throws IllegalAccessException
* @throws InstantiationException
*/
public List findObjForJdbc(String sql, int page, int rows,
Class clazz) {
List rsList = new ArrayList();
// 封装分页SQL
sql = JdbcDao.jeecgCreatePageSql(sql, page, rows);
List
function createwindowWithButton(title, addurl,width,height,OkFunc,CancelFunc) {
width = width?width:700;
height = height?height:520;
if(width=="100%" || height=="100%"){
width = window.top.document.body.offsetWidth;
height =window.top.document.body.offsetHeight-100;
}
//--author:JueYue---------date:20140427---------for:弹出bug修改,设置了zindex()函数
if(typeof(windowapi) == 'undefined'){
var returnobj = $.dialog({
content: 'url:'+addurl,
lock : true,
zIndex: getzIndex(),
width:width,
height:height,
title:title,
opacity : 0.3,
cache:false,
ok: eval(OkFunc),
cancelVal: '关闭',
cancel: eval(CancelFunc) /*为true等价于function(){}*/
});
}else{
/*W.*/
$.dialog({//使用W,即为使用顶级页面作为openner,造成打开的次级窗口获取不到关联的主窗口
content: 'url:'+addurl,
lock : true,
width:width,
zIndex:getzIndex(),
height:height,
parent:windowapi,
title:title,
opacity : 0.3,
cache:false,
ok: eval(OkFunc),
cancelVal: '关闭',
cancel: eval(CancelFunc) /*为true等价于function(){}*/
});
}
}
//调用代码
createwindowWithButton(
"驳回原因",
"dccInternalFileController.do?cancleC",
600,260,
function(){
iframe = this.iframe.contentWindow;
//-----------------------------
var fomrobjV = iframe.$("#formobj").Validform({tiptype:4});
var flag = false;
if(fomrobjV.check()){
var reason = iframe.$("#cancelRea").val();
//业务逻辑代码
//.........
//---------
flag = true;
}else{
flag = false;
}
if(flag){
return true;
}else{
return false;
}
},
function(){
return true;
}
)