增加一个案件增加或修改的接口

增加一个案件增加或修改的接口#头条创作挑战赛#需求描述:如果eventcode的值不存在则增加一条数据,如果eventcode的值存在则根据传参修改这条数据。

欢迎大家来到IT世界,在知识的湖畔探索吧!

#头条创作挑战赛#

需求描述:如果eventcode的值不存在则增加一条数据,如果eventcode的值存在则根据传参修改这条数据。

第一步

创建实体类和接收类

实体类

@Data
@Entity
@Table(name = "T_UMSM_EVENT_")
public class TUmEvent_ implements java.io.Serializable{


//    @SequenceGenerator(name = "generator" , allocationSize = 1, initialValue = 1, sequenceName = "SEQ")
//    @GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "generator")
    @Column(name = "EVENT_ID")
    private Long eventId;

    @Column(name = "INS_ID")
    private Long insId;

    @Column(name = "DEF_ID")
    private Integer defId;

    @Id
    @Column(name = "EVENTCODE")
    private String eventCode;

    @Column(name = "EVENT_CLASS")
    private String eventClass;

    @Column(name = "EVENT_DESC")
    private String eventDesc;

    @Column(name = "LOCATION_DESC")
    private String locationDesc;

    @Column(name = "LOCATIONX")
    private Double locationX;

    @Column(name = "LOCATIONY")
    private Double locationY;

    @Column(name = "KEYWORD")
    private String keyWord;

    @Column(name = "NOTE")
    private String note;

    @Column(name = "CREATETIME")
    private Date createTime;

    @Column(name = "CREATOR")
    private Long creator;

    @Column(name = "CREATEDEPT")
    private Long createDept;

    @Column(name = "SUPERVISOR")
    private Integer supervisor;

    @Column(name = "SUPERVISEDEPT")
    private Integer superviseDept;

    @Column(name = "VERSION")
    private Integer version;

    @Column(name = "ISDONE")
    private String isDone;

    @Column(name = "STATUS")
    private String status;

    @Column(name = "EVENTSOURCE_CODE")
    private String eventSourceCode;

    @Column(name = "COMPLAINANT")
    private String complainant;

    @Column(name = "CONTACTMODE")
    private String contactMode;

    @Column(name = "MOBILEEVENT_CODE")
    private String mobileEventCode;

    @Column(name = "DELAY")
    private String delay;

    @Column(name = "ISSCORE")
    private Integer isSCore;

    @Column(name = "ADVERT_ID")
    private Integer advertId;

    @Column(name = "ISSPECIAL")
    private String isSpecial;

    @Column(name = "SPECIALPLACE_ID")
    private Integer specialPlaceId;

    @Column(name = "SPECIALPLACE_XZQYID")
    private Integer specialPlaceXzqyId;

    @Column(name = "IS_SWAP")
    private Integer isSwap;

    @Column(name = "SWAP_OBJECT")
    private String swapObject;

    @Column(name = "MODIFY_TIME")
    private Date modifyTime;

    @Column(name = "XZQY_ID")
    private Integer xzqyId;

    @Column(name = "CURRENT_STEP_NAME")
    private String currentStepName;

    @Column(name = "CURRENT_DEPT")
    private String currentDept;

    @Column(name = "CURRENT_DEAL_PEOPLE")
    private String currentDealPeople;

}

欢迎大家来到IT世界,在知识的湖畔探索吧!

接收类

欢迎大家来到IT世界,在知识的湖畔探索吧!
@Data
public class ShowUmEvent {

    private Integer defId;

    private String eventCode;

    private String eventClass;

    private String eventDesc;

    private Integer xzqyId;

    private String status;

    private Date createTime;

    private String currentStepName;

    private String currentDept;

    private String currentDealPeople;
}

第二步

创建BaseService类BaseDao类和EventService类

BaseService类

public class BaseService {

    @Autowired
    protected BaseDao baseDao;

    /**
     * 参数获取及设置服务
     *
     * @param code:参数代码
     * @param defaultValue:若找不到记录,则返回该默认值
     **/
    public String getSysConfig(String code, String defaultValue) throws Exception {
        TSysConfig config = (TSysConfig) baseDao.getFirst("TSysConfig", "configCode=?", new Object[]{code});
        if (config != null)
            return config.getConfigValue();
        return defaultValue;
    }

    public Map<String, String> getSysConfig(Object[] codeArray, String defaultValue) throws Exception {
        List<TSysConfig> configList = null;
        Map<String, String> map = new HashMap<String, String>();
        if (codeArray != null && codeArray.length > 0) {
            StringBuffer where = new StringBuffer();
            for (int i = 0; i < codeArray.length; i++) {
                if (i != codeArray.length - 1) {
                    where.append(" configCode = ? or ");
                } else {
                    where.append(" configCode = ?");
                }
            }
            configList = baseDao.findByCondition("TSysConfig", where.toString(), codeArray);
            if (configList != null && configList.size() > 0) {
                for (int i = 0; i < configList.size(); i++) {
                    String configValue = configList.get(i).getConfigValue() == null ? defaultValue : configList.get(i).getConfigValue();
                    map.put(configList.get(i).getConfigCode(), configValue);
                }
            }
        }
        return map;
    }

    public String getKey(String keyname) throws Exception {
        Object[] inParams = new Object[]{keyname};
        Object[] outParams = new Object[]{""};
        int[] outParamtypes = new int[]{java.sql.Types.VARCHAR};
        Object[] results = baseDao.execProcedure("SP_KEYGENERATOR(?,?)", inParams, outParams, outParamtypes);
        if (results != null && results.length > 0)
            return results[0].toString();
        return null;
    }

    /**
     * 保存输入报文
     **/
    public void inLog(String logAction, HttpServletRequest request) throws Exception {
        TSysLog log = new TSysLog();
        log.setLogId(null);
        log.setLogType("01");
        log.setLogTime(new Date());
        log.setLogIp(request.getRemoteAddr());
        log.setLogAction(logAction);
        baseDao.save(log);
    }

    /**
     * 保存输出报文
     **/
    public void outLog(String logAction, HttpServletRequest request) throws Exception {
        TSysLog log = new TSysLog();
        log.setLogId(null);
        log.setLogType("02");
        log.setLogTime(new Date());
        log.setLogIp(request.getRemoteAddr());
        log.setLogAction(logAction);
        baseDao.save(log);
    }

    /**
     * 保存输入报文时发生异常,则将报文信息保存到日志文件当中
     **/
    public void inLogForException(String method, String logAction, HttpServletRequest request, Logger log) {
        StringBuffer logError = new StringBuffer("手机端调用接口-").append(method).append(":保存输入报文时发生异常。");
        logError.append("IP:").append(request.getRemoteAddr()).append(",");
        logError.append("时间:").append(new Date());
        logError.append("报文:").append(logAction);
        log.error(logError.toString());
    }

    /**
     * 保存输出报文时发生异常,则将报文信息保存到日志文件当中
     **/
    public void outLogForException(String method, String logAction, HttpServletRequest request, Logger log) {
        StringBuffer logError = new StringBuffer("手机端调用接口-").append(method).append(":保存输出报文时发生异常。");
        logError.append("IP:").append(request.getRemoteAddr()).append(",");
        logError.append("时间:").append(new Date());
        logError.append("报文:").append(logAction);
        log.error(logError.toString());
    }

    public void saveOrUpdateByMerge(Object object) throws Exception {
        baseDao.merge(object);
    }

    public void flush() throws Exception {
        baseDao.flush();
    }

    public void clear() throws Exception {
        baseDao.clear();
    }
}

BaseDao类

欢迎大家来到IT世界,在知识的湖畔探索吧!public class BaseDao extends HibernateDaoSupport {

    private Logger log = Logger.getLogger(this.getClass());

    /**
     * 插入记录
     *
     * @param object:需要保存的对像
     * @author 
     **/
    public void save(Object object) {
        log.debug("saving " + object.getClass().getName() + " instance");
        try {
            //getHibernateTemplate().clear();
            getHibernateTemplate().save(object);
            log.debug("save successful");
        } catch (RuntimeException re) {
            log.error("save failed", re);
            throw re;
        }
    }

    /**
     * 更新记录
     *
     * @param object:需要保存的对像
     * @author 
     **/
    public void update(Object object) {
        log.debug("updating " + object.getClass().getName() + " instance");
        try {
            //getHibernateTemplate().clear();
            getHibernateTemplate().update(object);
            log.debug("update successful");
        } catch (RuntimeException re) {
            log.error("update failed", re);
            throw re;
        }
    }

    /**
     * 插入或者更新记录
     *
     * @param object:需要保存或者更新的对像
     * @author 
     **/
    public void saveOrUpdate(Object object) {
        log.debug("saveOrUpdate " + object.getClass().getName() + " instance");
        try {
            getHibernateTemplate().saveOrUpdate(object);

            log.debug("saveOrUpdate successful");
        } catch (RuntimeException re) {
            log.error("saveOrUpdate failed", re);
            throw re;
        }
    }


    /**
     * 插入或者更新多条记录的集合
     *
     * @param object:需要保存或者更新的对像
     * @author 
     **/
    public void saveOrUpdateList(List list) {
        log.debug("saveOrUpdateint list instance");
        try {
            getHibernateTemplate().saveOrUpdateAll(list);
            log.debug("saveOrUpdate successful");
        } catch (RuntimeException re) {
            log.error("saveOrUpdate failed", re);
            throw re;
        }
    }

    /**
     * 删除记录
     *
     * @param object:需要删除的对像
     * @author 
     **/
    public void delete(Object object) {
        log.debug("deleting " + object.getClass().getName() + " instance");
        try {
            getHibernateTemplate().delete(object);
            log.debug("delete successful");
        } catch (RuntimeException re) {
            log.error("delete failed", re);
            throw re;
        }
    }

    /**
     * 删除多条记录集合
     *
     * @param object:需要删除的对像
     * @author 
     **/
    public void deleteList(List list) {
        log.debug("deleting list instance");
        try {
            getHibernateTemplate().deleteAll(list);
            log.debug("delete successful");
        } catch (RuntimeException re) {
            log.error("delete failed", re);
            throw re;
        }
    }

    /**
     * 根据条件删除记录
     *
     * @param tableName:Pojo类的类名,例如:Demo
     * @param condition:条件
     * @param value:属性值
     **/
    public void deleteByCondition(String tableName, String condition, Object[] values) {
        log.debug("deleting " + tableName + " by condition:" + condition);
        try {
            getHibernateTemplate().bulkUpdate("delete from " + tableName + " where " + condition, values);
            log.debug("delete successful");
        } catch (RuntimeException re) {
            log.error("delete failed", re);
            throw re;
        }
    }

    /**
     * 执行HQL语句
     *
     * @param tableName:Pojo类的类名,例如:Demo
     * @param condition:条件
     * @param value:属性值
     **/
    public void execByHql(String hql) {
        log.debug("exec by hql:" + hql);
        try {
            getHibernateTemplate().bulkUpdate(hql);
            log.debug("exec successful");
        } catch (RuntimeException re) {
            log.error("exec failed", re);
            throw re;
        }
    }

    public void execByHql(String hql, Object[] objects) {
        log.debug("exec by hql:" + hql);
        try {
            getHibernateTemplate().bulkUpdate(hql, objects);
            log.debug("exec successful");
        } catch (RuntimeException re) {
            log.error("exec failed", re);
            throw re;
        }
    }

    //执行原生 sql
    public void executeBySql(final String sql) {
        try {
            getHibernateTemplate().execute(new HibernateCallback() {

                @Override
                public Object doInHibernate(Session session) throws HibernateException, SQLException {
                    Connection conn = null;
                    PreparedStatement ps = null;
                    try {
                        conn = SessionFactoryUtils.getDataSource(getSessionFactory()).getConnection();
                        ps = conn.prepareStatement(sql);
                        ps.execute();
                    } catch (Exception e) {
                    } finally {
                        ps.close();
                        conn.close();
                    }
                    return null;
                }
            });
        } catch (Exception e) {
        }
    }



    /**
     * 执行sql返回原生的resultset
     *
     * @param sql
     * @throws SQLException
     */
    public ResultSet executeRs(final String sql) {

        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = SessionFactoryUtils.getDataSource(getSessionFactory()).getConnection();
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
        } catch (Exception e) {
            System.out.println("查询有问题!!");
        }
        return rs;
    }

    /**
     * 根据SQL查询总数
     *
     * @param sql    sql语句
     * @param values 参数(无参数时可用null代替)
     * @return 返回一个int类型的总数
     * @throws Exception
     */
    public int countBySql1(final String sql, final List values) throws Exception {
        int count = 0;
        List list = getHibernateTemplate().executeFind(new HibernateCallback() {
            @Override
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                List list = null;
                try {
                    String sqlcount = sql;
                    Query query = session.createSQLQuery(sqlcount).addScalar("COUNT", Hibernate.INTEGER);
                    if (values != null && values.size() > 0) {
                        for (int i = 0; i < values.size(); i++) {
                            query.setParameter(i, values.get(i));
                        }
                    }
                    list = query.list();

                } catch (RuntimeException re) {
                    log.error("find by sql failed", re);
                    throw re;
                }
                return list;
            }
        });
        if (list != null) {
            count = (Integer) list.get(0);
        }
        return count;
    }


    /**
     * 执行sql返回原生的resultset
     *
     * @param sql    执行的sql语句
     * @param params 带过来的参数
     * @throws SQLException
     */
    public ResultSet executeRs(final String sql, Object[] params) {

        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = SessionFactoryUtils.getDataSource(getSessionFactory()).getConnection();
            ps = conn.prepareStatement(sql);
            if (params != null && params.length > 0) {
                for (int i = 0; i < params.length; i++) {
                    ps.setObject(i + 1, params[i]);
                }
            }
            rs = ps.executeQuery();
        } catch (Exception e) {
            System.out.println("查询有问题!!");
        }
        return rs;
    }

    /**
     * 执行sql返回原生的preparedstatement
     *
     * @param sql
     * @throws SQLException
     */
    public PreparedStatement getPs(final String sql) {

        Connection conn = null;
        PreparedStatement ps = null;

        try {
            conn = SessionFactoryUtils.getDataSource(getSessionFactory()).getConnection();
            ps = conn.prepareStatement(sql);
        } catch (Exception e) {
            System.out.println("查询有问题!!");
        }
        return ps;
    }

    /**
     * 根据主键查询记录
     *
     * @param tableName:Pojo类的类名,例如:com.zhongkai.model.Demo
     * @param primaryKey:主键(任意封装数据类型,例如Integer、String)
     * @author
     **/
    public Object findById(String tableName, Serializable primaryKey) {
        log.debug("getting " + tableName + " instance with primaryKey: " + primaryKey);
        try {
            Object instance = (Object) getHibernateTemplate().get(tableName, primaryKey);
            return instance;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
    }

    /**
     * 根据主键查询记录
     *
     * @param tableName:Pojo类的class,例如:Demo
     * @param primaryKey:主键(任意封装数据类型,例如Integer、String)
     * @author 
     **/
    public Object findById(Class tableClass, Serializable primaryKey) {
        log.info("getting " + tableClass.getClass().getName() + " instance with primaryKey: " + primaryKey);
        try {
            Object instance = (Object) getHibernateTemplate().get(tableClass, primaryKey);
            return instance;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
    }

    /**
     * 根据某条记录查询相同内容的记录
     *
     * @param object:模型记录
     * @author
     **/
    public List findByExample(Object object) {
        log.debug("finding " + object.getClass().getName() + " instance by example");
        try {
            List results = (List) getHibernateTemplate()
                    .findByExample(object);
            log.debug("find by example successful, result size: "
                    + results.size());
            return results;
        } catch (RuntimeException re) {
            log.error("find by example failed", re);
            throw re;
        }
    }

    /**
     * 根据某字段查询(单字段)
     *
     * @param tableName:Pojo类的类名,例如:Demo
     * @param propertyName:属性名
     * @param value:属性值
     * @author
     **/
    public List findByProperty(String tableName, String propertyName, Object value) {
        log.debug("finding " + tableName + " instance with property: " + propertyName
                + ", value: " + value);
        try {
            String queryString = "from " + tableName + " as model where model."
                    + propertyName + "= ?";
            return getHibernateTemplate().find(queryString, value);
        } catch (RuntimeException re) {
            log.error("find by property failed", re);
            throw re;
        }
    }

    /**
     * 根据条件查询
     *
     * @param tableName:Pojo类的类名,例如:Demo
     * @param condition:查询条件
     * @param value:属性值
     * @author 
     **/
    public List findByCondition(String tableName, String condition, Object[] values) {
        log.debug("finding " + tableName + " instance with condition: " + condition);
        try {
            String queryString = "from " + tableName + " where " + condition;
            return getHibernateTemplate().find(queryString, values);
        } catch (RuntimeException re) {
            log.error("find by condition failed", re);
            throw re;
        }
    }

    /**
     * 根据某字段查询(单字段)
     *
     * @param tableName:Pojo类的类名,例如:Demo
     * @author
     **/
    public List findAll(String tableName) {
        log.debug("finding all " + tableName + " instances");
        try {
            String queryString = "from " + tableName;
            return getHibernateTemplate().find(queryString);
        } catch (RuntimeException re) {
            log.error("find all failed", re);
            throw re;
        }
    }

    /**
     * 根据自定义HQL语句查询(不可带?号参数)
     *
     * @param queryString:hql语句
     * @author 
     **/
    public List findByHql(String queryString) {
        //log.debug("finding by hql:"+queryString);
        try {
            return getHibernateTemplate().find(queryString);
        } catch (RuntimeException re) {
            log.error("find by hql failed", re);
            throw re;
        }
    }

    /**
     * 根据自定义HQL语句查询(可带?号参数)
     *
     * @param queryString:hql语句
     * @param values:参数值
     * @author 
     **/
    public List findByHql(String queryString, Object[] values) {
        log.debug("finding by hql:" + queryString);
        try {
            return getHibernateTemplate().find(queryString, values);
        } catch (RuntimeException re) {
            log.error("find by hql failed", re);
            throw re;
        }
    }

    /**
     * 根据条件查询获取第一条记录
     *
     * @param tableName:Pojo类的类名,例如:Demo
     * @param condition:查询条件
     * @param value:属性值
     * @author 
     **/
    public Object getFirst(final String tableName, final String condition, final Object[] values) {
        log.debug("finding " + tableName + " instance with condition: " + condition);
        try {
            List list = getHibernateTemplate().executeFind(new HibernateCallback() {
                public Object doInHibernate(Session session) throws HibernateException,
                        SQLException {
                    String queryString = "from " + tableName + " where " + condition;
                    Query query = session.createQuery(queryString);
                    if (values != null && values.length > 0) {
                        for (int i = 0; i < values.length; i++) {
                            query.setParameter(i, values[i]);
                        }
                    }
                    query.setFirstResult(0);
                    query.setMaxResults(1);
                    List results = query.list();
                    return results;
                }
            });
            if (list != null && list.size() > 0)
                return list.get(0);
            return null;
        } catch (RuntimeException re) {
            log.error("find by hql failed", re);
            throw re;
        }
    }

    /**
     * 根据自定义HQL语句查询,获取第一记录(不可带?号参数)
     *
     * @param queryString:hql语句
     * @author 
     **/
    public Object getFirst(final String queryString) {
        log.debug("finding by hql:" + queryString);
        try {
            List list = getHibernateTemplate().executeFind(new HibernateCallback() {
                public Object doInHibernate(Session session) throws HibernateException,
                        SQLException {
                    Query query = session.createQuery(queryString);
                    query.setFirstResult(0);
                    query.setMaxResults(1);
                    List results = query.list();
                    return results;
                }
            });
            if (list != null && list.size() > 0)
                return list.get(0);
            return null;
        } catch (RuntimeException re) {
            log.error("find by hql failed", re);
            throw re;
        }
    }

    /**
     * 根据自定义HQL语句查询,获取第一条记录(可带?号参数)
     *
     * @param queryString:hql语句
     * @param values:参数值
     * @author 
     **/
    public Object getFirst(final String queryString, final Object[] values) {
        log.debug("finding by hql:" + queryString);
        try {
            List list = getHibernateTemplate().executeFind(new HibernateCallback() {
                public Object doInHibernate(Session session) throws HibernateException,
                        SQLException {
                    Query query = session.createQuery(queryString);
                    if (values != null && values.length > 0) {
                        for (int i = 0; i < values.length; i++) {
                            query.setParameter(i, values[i]);
                        }
                    }
                    query.setFirstResult(0);
                    query.setMaxResults(1);
                    List results = query.list();
                    return results;
                }
            });
            if (list != null && list.size() > 0)
                return list.get(0);
            return null;
        } catch (RuntimeException re) {
            log.error("find by hql failed", re);
            throw re;
        }
    }

    /**
     * 根据条件统计记录数
     *
     * @param tableName:Pojo类的类名,例如:Demo
     * @param condition:查询条件
     * @param value:属性值
     * @author 
     **/
    public int countByCondition(String tableName, String condition, Object[] values) {
        log.debug("counting " + tableName + " instance with condition: " + condition);
        try {
            String queryString = "select count(*) from " + tableName;
            if (condition != null && !condition.equals(""))
                queryString += " where " + condition;
            List list = getHibernateTemplate().find(queryString, values);
            int count = ((Long) list.get(0)).intValue();
            return count;
        } catch (RuntimeException re) {
            log.error("count by condition failed", re);
            throw re;
        }
    }

    /**
     * 根据条件统计记录数
     *
     * @param tableName:Pojo类的类名,例如:Demo
     * @param condition:查询条件
     * @author 
     **/
    public int countByHql(String hql) {
        log.debug("counting by hql:" + hql);
        try {
            String queryString = "select count(*) " + hql;
            List list = getHibernateTemplate().find(queryString);
            int count = ((Long) list.get(0)).intValue();
            return count;
        } catch (RuntimeException re) {
            log.error("count by condition failed", re);
            throw re;
        }
    }

    //查询个数.
    public long countByHqlForUnique(final String queryString) {
        Long count = Long.valueOf(0);
        List list = getHibernateTemplate().executeFind(new HibernateCallback() {

            @Override
            public Object doInHibernate(Session session)
                    throws HibernateException, SQLException {
                Query query = session.createQuery(queryString);
                Long size = (Long) query.uniqueResult();
//              System.out.println("long size = " + size);
                List<Long> sizeList = new ArrayList<Long>();
                sizeList.add(size);
                return sizeList;
            }

        });
        if (list != null) {
            count = (Long) list.get(0);
        }
        return count;
    }

    //查询个数.
    public long countByHqlForUnique(final String queryString, final Object[] values) {
        Long count = Long.valueOf(0);
        List list = getHibernateTemplate().executeFind(new HibernateCallback() {

            @Override
            public Object doInHibernate(Session session)
                    throws HibernateException, SQLException {
                Query query = session.createQuery(queryString);
                if (values != null && values.length > 0) {
                    for (int i = 0; i < values.length; i++) {
                        query.setParameter(i, values[i]);
                    }
                }
                Long size = (Long) query.uniqueResult();
                List<Long> sizeList = new ArrayList<Long>();
                sizeList.add(size);
                return sizeList;
            }

        });
        if (list != null) {
            count = (Long) list.get(0);
        }
        return count;
    }

    public int countBySqlForUnique(final String queryString, final Object[] values) {
        int count = 0;
        List list = getHibernateTemplate().executeFind(new HibernateCallback() {

            @Override
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                List doList = null;
                Query query = session.createSQLQuery(queryString);
                if (values != null && values.length > 0) {
                    for (int i = 0; i < values.length; i++) {
                        query.setParameter(i, values[i]);
                    }
                }
                doList = query.list();
                return doList;
            }

        });
        if (list != null) {
            count = Integer.valueOf(list.get(0).toString());
        }
        return count;
    }

    public List findByHql(final String queryString, final String variableName, final List list) {
        List returnList = getHibernateTemplate().executeFind(new HibernateCallback() {

            @Override
            public Object doInHibernate(Session session)
                    throws HibernateException, SQLException {
                Query query = session.createQuery(queryString);
                query.setParameterList(variableName, list);
                return query.list();
            }

        });
        return returnList;
    }


    public List findByHql(final String queryString, final String variableName, final List list, final Integer pageIndex, final Integer pageMax) {
        log.debug("finding by hql:" + queryString);
        try {
            List returnList = getHibernateTemplate().executeFind(new HibernateCallback() {

                @Override
                public Object doInHibernate(Session session)
                        throws HibernateException, SQLException {
                    Query query = session.createQuery(queryString);
                    query.setParameterList(variableName, list);
                    query.setFirstResult((pageIndex.intValue() - 1)
                            * pageMax.intValue());
                    query.setMaxResults(pageMax);
                    List results = query.list();
                    return results;
                }

            });
            return returnList;
        } catch (RuntimeException re) {
            log.error("find by hql failed", re);
            throw re;
        }
    }

    public List findByHql(final String queryString, final Object[] valuesName, final Object[] values, final Integer pageIndex, final Integer pageMax) throws Exception {
        log.debug("finding by hql:" + queryString);
        try {
            List returnList = getHibernateTemplate().executeFind(new HibernateCallback() {

                @Override
                public Object doInHibernate(Session session)
                        throws HibernateException, SQLException {
                    Query query = session.createQuery(queryString);
                    if (valuesName != null) {
                        for (int i = 0; i < valuesName.length; i++) {
                            Object object = values[i];
                            if (object.getClass().equals(ArrayList.class)) {
                                query.setParameterList((String) valuesName[i], (ArrayList) object);
                            } else if (object.getClass().equals(Long[].class)) {
                                query.setParameterList((String) valuesName[i], (Long[]) object);
                            } else if (object.getClass().equals(String[].class)) {
                                query.setParameterList((String) valuesName[i], (String[]) object);
                            } else if (object.getClass().equals(Long.class)) {
                                query.setParameter((String) valuesName[i], (Long) object);
                            } else if (object.getClass().equals(Integer.class)) {
                                query.setParameter((String) valuesName[i], (Integer) object);
                            } else {
                                query.setParameter((String) valuesName[i], object);
                            }
                        }
                    }
                    if (pageIndex != 0 && pageMax != 0) {
                        query.setFirstResult((pageIndex.intValue() - 1)
                                * pageMax.intValue());
                        query.setMaxResults(pageMax);
                    }
                    List results = query.list();
                    return results;
                }

            });
            return returnList;
        } catch (RuntimeException re) {
            log.error("find by hql failed", re);
            throw re;
        }
    }

    /**
     * 根据自定义HQL语句查询(用于分页)
     *
     * @param queryString:hql语句
     * @param pageIndex:开头
     * @param pageMax:结尾
     * @author 
     **/
    public List findByHql(final String queryString, final Integer pageIndex, final Integer pageMax) {
        log.debug("finding by hql:" + queryString);
        try {
            return getHibernateTemplate().executeFind(new HibernateCallback() {
                public Object doInHibernate(Session session) throws HibernateException,
                        SQLException {
                    Query query = session.createQuery(queryString);
                    query.setFirstResult((pageIndex.intValue() - 1)
                            * pageMax.intValue());
                    query.setMaxResults(pageMax);
                    List results = query.list();
                    return results;
                }
            });
        } catch (RuntimeException re) {
            log.error("find by hql failed", re);
            throw re;
        }
    }

    /**
     * 根据SQL查询
     * sql:sql语句
     *
     * @author 
     **/
    public List findBySql(final String sql) throws Exception {
        log.debug("finding by sql:" + sql);
        return getHibernateTemplate().executeFind(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                Connection connection = null;
                ResultSet rs = null;
                PreparedStatement pstmt = null;
                ArrayList list = null;
                try {
                    connection = session.connection();
                    pstmt = connection.prepareStatement(sql);
                    rs = pstmt.executeQuery();
                    ResultSetMetaData meta = rs.getMetaData();
                    int mc = meta.getColumnCount();
                    list = new ArrayList();
                    while (rs.next()) {
                        HashMap map = new HashMap();
                        String tempValue;
                        String columnName;
                        for (int i = 1; i <= mc; i++) {
                            tempValue = rs.getString(i) == null ? "" : rs.getString(i);
                            columnName = meta.getColumnName(i);
                            columnName = columnName.toUpperCase();
                            map.put(columnName, tempValue);
                        }
                        list.add(map);
                    }
                } catch (RuntimeException re) {
                    log.error("find by sql failed", re);
                    throw re;
                } finally {
                    if (rs != null)
                        rs.close();
                    if (pstmt != null) {
                        pstmt.clearParameters();
                        pstmt.close();
                    }
                    if (connection != null)
                        connection.close();
                }
                return list;
            }
        });
    }

    /**
     * 根据HQL命名查询(查)
     *
     * @param hqlNameQuery:命名查询实例名
     * @param values:参数值
     * @author 
     **/
    public List findByHqlNameQuery(String hqlNameQuery, Object[] values) {
        log.debug("finding by hqlNameQuery:" + hqlNameQuery);
        try {
            return getHibernateTemplate().findByNamedQuery(hqlNameQuery, values);
        } catch (RuntimeException re) {
            log.error("find by hqlNameQuery failed", re);
            throw re;
        }
    }

    /**
     * 根据SQL命名查询
     * sqlNameQuery:命名查询实例名
     *
     * @throws SQLException
     * @author 
     **/
    public List findBySqlNameQuery(final String sqlNameQuery, final Object[] values) throws SQLException {
        log.debug("finding by sqlNameQuery:" + sqlNameQuery);
        return getHibernateTemplate().executeFind(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                Connection connection = null;
                PreparedStatement pstmt = null;
                ResultSet rs = null;
                ArrayList list = null;
                try {
                    Query query = session.getNamedQuery(sqlNameQuery);
                    String sql = query.getQueryString();
                    connection = session.connection();
                    pstmt = connection.prepareStatement(sql);
                    System.out.println("JDBC:" + sql);
                    if (values != null && values.length > 0) {
                        for (int i = 0; i < values.length; i++) {
                            pstmt.setObject(i + 1, values[i]);
                        }
                    }
                    rs = pstmt.executeQuery();
                    ResultSetMetaData meta = rs.getMetaData();
                    int mc = meta.getColumnCount();
                    list = new ArrayList();
                    while (rs.next()) {
                        HashMap map = new HashMap();
                        String tempValue;
                        String columnName;
                        for (int i = 1; i <= mc; i++) {
                            tempValue = rs.getString(i) == null ? "" : rs.getString(i);
                            columnName = meta.getColumnName(i);
                            columnName = columnName.toUpperCase();
                            map.put(columnName, tempValue);
                        }
                        list.add(map);
                    }
                } catch (RuntimeException re) {
                    log.error("find by sqlNameQuery failed", re);
                    throw re;
                } finally {
                    if (rs != null)
                        rs.close();
                    if (pstmt != null)
                        pstmt.close();
                    if (connection != null)
                        connection.close();
                }
                return list;
            }
        });
    }

    public List findBySqlNameQuery(final String sqlNameQuery, final Object[] values, final Integer pageIndex, final Integer pageMax) throws SQLException {
        log.debug("finding by sqlNameQuery:" + sqlNameQuery);
        return getHibernateTemplate().executeFind(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                Connection connection = null;
                PreparedStatement pstmt = null;
                ResultSet rs = null;
                List list = null;
                try {
                    Query query = session.getNamedQuery(sqlNameQuery);
                    String sql = query.getQueryString();
                    if (values != null && values.length > 0) {
                        for (int i = 0; i < values.length; i++) {
                            query.setParameter(i, values[i]);
                        }
                    }
                    if (pageMax != 0) {
                        query.setFirstResult((pageIndex.intValue() - 1)
                                * pageMax.intValue());
                        query.setMaxResults(pageMax);
                    }
                    list = query.list();
                    return list;
                } catch (RuntimeException re) {
                    log.error("find by sqlNameQuery failed", re);
                    return null;
                } finally {
                    if (rs != null)
                        rs.close();
                    if (pstmt != null)
                        pstmt.close();
                    if (connection != null)
                        connection.close();
                }
            }
        });
    }

    /**
     * 根据SQL命名查询解决sql中带有in(?)“:valuesName” 代替“?”
     * sqlNameQuery:命名查询实例名
     *
     * @throws SQLException valuesName为参数命
     *                      values 可以是List也可以是数组!
     * @author 梁远剑
     **/
    public List findBySql(final String sqlNameQuery, final Object[] valuesName, final Object[] values, final Integer pageIndex, final Integer pageMax) throws Exception {
        log.debug("finding by sql:" + sqlNameQuery);
        return getHibernateTemplate().executeFind(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                List list = null;
                try {
                    Query query = session.getNamedQuery(sqlNameQuery);//session.createSQLQuery(sql).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
                    query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
                    String sql = query.getQueryString();
                    if (pageMax != 0) {
                        query.setFirstResult((pageIndex.intValue() - 1)
                                * pageMax.intValue());
                        query.setMaxResults(pageMax);
                    }
                    if (valuesName != null && values != null) {
                        for (int i = 0; i < values.length; i++) {
                            Object object = values[i];
                            if (object.getClass().equals(ArrayList.class)) {
                                query.setParameterList((String) valuesName[i], (ArrayList) object);
                            } else if (object.getClass().equals(Long[].class)) {
                                query.setParameterList((String) valuesName[i], (Long[]) object);
                            } else if (object.getClass().equals(String[].class)) {
                                query.setParameterList((String) valuesName[i], (String[]) object);
                            } else {
                                query.setParameter((String) valuesName[i], object);
                            }
                        }
                    }
                    System.out.println("JDBC:" + sql);
                    list = query.list();
                } catch (RuntimeException re) {
                    log.error("find by sql failed", re);
                    throw re;
                }
                return list;
            }
        });
    }

    public List findBySqlNameQuery(final String sqlNameQuery, final Object[] valuesName, final Object[] values) throws SQLException {
        log.debug("finding by sqlNameQuery:" + sqlNameQuery);
        return getHibernateTemplate().executeFind(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                Connection connection = null;
                PreparedStatement pstmt = null;
                ResultSet rs = null;
                ArrayList list = null;
                try {
                    Query query = session.getNamedQuery(sqlNameQuery);
                    String sql = query.getQueryString();
                    connection = session.connection();
                    pstmt = connection.prepareStatement(sql);
                    System.out.println("JDBC:" + sql);
                    if (values != null && values.length > 0) {
                        for (int i = 0; i < values.length; i++) {
                            pstmt.setObject(i + 1, values[i]);
//                          pstmt.
                        }
                    }
                    rs = pstmt.executeQuery();
                    ResultSetMetaData meta = rs.getMetaData();
                    int mc = meta.getColumnCount();
                    list = new ArrayList();
                    while (rs.next()) {
                        HashMap map = new HashMap();
                        String tempValue;
                        String columnName;
                        for (int i = 1; i <= mc; i++) {
                            tempValue = rs.getString(i) == null ? "" : rs.getString(i);
                            columnName = meta.getColumnName(i);
                            columnName = columnName.toUpperCase();
                            map.put(columnName, tempValue);
                        }
                        list.add(map);
                    }
                } catch (RuntimeException re) {
                    log.error("find by sqlNameQuery failed", re);
                    throw re;
                } finally {
                    if (rs != null)
                        rs.close();
                    if (pstmt != null)
                        pstmt.close();
                    if (connection != null)
                        connection.close();
                }
                return list;
            }
        });
    }

    /**
     * 根据HQL命名查询(查)
     *
     * @param hqlNameQuery:命名查询实例名
     * @param values:参数值
     * @author 
     **/
    public int execByHqlNameQuery(String hqlNameQuery, Object[] values) {
        log.debug("exec by hqlNameQuery:" + hqlNameQuery);
        try {
            String hql = getHibernateTemplate().getSessionFactory().openSession().getNamedQuery(hqlNameQuery).getQueryString();
            return getHibernateTemplate().bulkUpdate(hql, values);
        } catch (RuntimeException re) {
            log.error("exec by hqlNameQuery failed", re);
            throw re;
        }
    }

    /**
     * 根据HQL命名查询(查)
     *
     * @param hqlNameQuery:命名查询实例名
     * @param values:参数值
     * @author 
     **/
    public int execBySqlNameQuery(final String hqlNameQuery, final Object[] values) {
        log.debug("exec by sqlNameQuery:" + hqlNameQuery);
        try {
            return (Integer) getHibernateTemplate().execute(new HibernateCallback() {
                @Override
                public Object doInHibernate(Session session)
                        throws HibernateException, SQLException {
                    Transaction tx = session.getTransaction();
                    Query query = session.getNamedQuery(hqlNameQuery);
                    String hql = query.getQueryString();
                    if (values != null && values.length > 0) {
                        for (int i = 0; i < values.length; i++) {
                            query.setParameter(i + 1, values[i]);
                        }
                    }
                    tx.begin();
                    int result = 0;
                    try {
                        result = query.executeUpdate();
                        tx.commit();
                    } catch (RuntimeException e) {
                        tx.rollback();
                        e.printStackTrace();
                    }
                    session.close();
                    return result;
                }

            });
        } catch (RuntimeException re) {
            log.error("exec by sqlNameQuery failed", re);
            throw re;
        }
    }

    /**
     * 根据HQL命名查询(查)
     *
     * @param hqlNameQuery:命名查询实例名
     * @param values:参数值
     * @author 
     **/
    public int execBySqlNameQuery(final String hqlNameQuery, final Map values) {
        log.debug("exec by sqlNameQuery:" + hqlNameQuery);
        try {
            return (Integer) getHibernateTemplate().execute(new HibernateCallback() {
                @Override
                public Object doInHibernate(Session session)
                        throws HibernateException, SQLException {
                    //Transaction tx=session.getTransaction();
                    Query query = session.getNamedQuery(hqlNameQuery);
                    String hql = query.getQueryString();
                    query.setProperties(values);

//                  if(values!=null && values.length>0){
//                      for(int i=0;i<values.length;i++){
//                          query.setParameter(i+1, values[i]);
//                      }
//                  }
                    //tx.begin();
                    int result = 0;
                    try {
                        result = query.executeUpdate();
                        //tx.commit();
                    } catch (RuntimeException e) {
                        //tx.rollback();
                        e.printStackTrace();
                    }
                    //session.close();
                    return result;
                }

            });
        } catch (RuntimeException re) {
            log.error("exec by sqlNameQuery failed", re);
            throw re;
        }
    }

    public static BaseDao getFromApplicationContext(ApplicationContext ctx) {
        return (BaseDao) ctx.getBean("baseDao");
    }

    /**
     * 执行存储过程
     *
     * @param procedure:存储过程名称
     * @param values:参数值
     * @throws SQLException
     * @author 
     **/
    public Object[] execProcedure(String procName, Object[] inParams, Object[] outParams, int[] outParamstypes) throws SQLException {
        Connection connection = null;
        CallableStatement call = null;
        try {
            connection = SessionFactoryUtils.getDataSource(getSessionFactory()).getConnection();
            call = connection.prepareCall("{call " + procName + "}");
            int inParamsLength = 0;
            if (inParams != null) {
                inParamsLength = inParams.length;
                for (int i = 0; i < inParamsLength; i++) {
                    call.setObject(i + 1, inParams[i]);
                }

            }
            int outParamsLength = 0;
            if (outParams != null) {
                outParamsLength = outParams.length;
                for (int j = 0; j < outParamsLength; j++) {
                    call.registerOutParameter(inParamsLength + j + 1, outParamstypes[j]);
                }
            }
            call.executeUpdate();
            Object[] outValues = new Object[outParamsLength];
            for (int i = 0; i < outValues.length; i++) {
                outValues[i] = call.getObject(inParamsLength + i + 1);
            }
            return outValues;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        } finally {
            if (connection != null)
                connection.close();
            if (call != null)
                call.close();
        }
    }

    /**
     * 缓存查询
     **/
    public List findByHqlForCache(final String queryString) throws Exception {
        return getHibernateTemplate().executeFind(new HibernateCallback() {
            public Object doInHibernate(Session s) throws HibernateException, SQLException {
                Query query = s.createQuery(queryString);
                List results = query.setCacheable(true).list();
                return results;
            }
        });
    }

    public void merge(Object object) throws Exception {
        getHibernateTemplate().merge(object);
    }

    /**
     * 根据SQL命名查询
     * sqlNameQuery:命名查询实例名
     *
     * @throws SQLException
     * @author 
     **/
    public List findBySqlNameQueryFromMap(final String sqlNameQuery, final Map values) throws SQLException {
        log.debug("finding by sqlNameQuery:" + sqlNameQuery);
        return getHibernateTemplate().executeFind(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                List list = null;
                try {
                    Query query = session.getNamedQuery(sqlNameQuery);
                    query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
                    String sql = query.getQueryString();
                    query.setProperties(values);
                    list = query.list();
                } catch (RuntimeException re) {
                    log.error("find by sqlNameQuery failed", re);
                    throw re;
                } finally {
                }
                return list;
            }
        });
    }

    public List findBySqlNameQueryFromMap(final String sqlNameQuery, final Map values, final Integer pageIndex, final Integer pageMax) throws SQLException {
        log.debug("finding by sqlNameQuery:" + sqlNameQuery);
        return getHibernateTemplate().executeFind(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                List list = null;
                try {
                    Query query = session.getNamedQuery(sqlNameQuery);
                    String sql = query.getQueryString();
                    query.setProperties(values);
                    if (pageMax != 0) {
                        query.setFirstResult((pageIndex.intValue() - 1)
                                * pageMax.intValue());
                        query.setMaxResults(pageMax);
                    }
                    list = query.list();
                } catch (RuntimeException re) {
                    log.error("find by sqlNameQuery failed", re);
                    throw re;
                } finally {
                }
                return list;
            }
        });
    }

    public List findBySql(final String sql, final String name, final List value) throws Exception {
        log.debug("finding by sql:" + sql);
        return getHibernateTemplate().executeFind(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                List list = null;
                try {
                    Query query = session.createSQLQuery(sql).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
                    String sql = query.getQueryString();
                    query.setParameterList(name, value);
                    System.out.println("JDBC:" + sql);
                    list = query.list();
                } catch (RuntimeException re) {
                    log.error("find by sql failed", re);
                    throw re;
                }
                return list;
            }
        });
    }

    /**
     * 根据SQL查询(可代?参数)
     *
     * @param sql       sql语句
     * @param values    Object数组型参数(如无参数请用null代替)
     * @param pageIndex 起始位置
     * @param pageMax   每页显示最大数
     * @return 返回一个包含Map(字段全大写)的List
     * @throws Exception
     */
    public List findBySql(final String sql, final Object[] values, final Integer pageIndex, final Integer pageMax) throws Exception {
        return getHibernateTemplate().executeFind(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                List list = null;
                try {
                    Query query = session.createSQLQuery(sql).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
                    String sql = query.getQueryString();
                    if (values != null && values.length > 0) {
                        for (int i = 0; i < values.length; i++) {
                            query.setParameter(i, values[i]);
                        }
                    }

                    if (pageIndex != 0 && pageMax != 0) {
                        query.setFirstResult((pageIndex.intValue() - 1)
                                * pageMax.intValue());
                        query.setMaxResults(pageMax);
                    }

                    list = query.list();
                } catch (RuntimeException re) {
                    log.error("find by sql failed", re);
                    throw re;
                }
                return list;
            }
        });
    }

    /**
     * 根据SQL查询(可代?参数)
     *
     * @param sql       sql语句
     * @param values    Object数组型参数(如无参数请用null代替)
     * @param pageIndex 起始位置
     * @param pageMax   每页显示最大数
     * @return 返回一个包含Map(字段全大写)的List
     * @throws Exception
     */
    public List findBySqlList(final String sql, final List values, final Integer pageIndex, final Integer pageMax) throws Exception {
        return getHibernateTemplate().executeFind(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                List list = null;
                try {
                    Query query = session.createSQLQuery(sql).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
                    String sql = query.getQueryString();
                    if (values != null && values.size() > 0) {
                        for (int i = 0; i < values.size(); i++) {
                            query.setParameter(i, values.get(i));
                        }
                    }
                    query.setFirstResult((pageIndex.intValue() - 1)
                            * pageMax.intValue());
                    query.setMaxResults(pageMax);
                    list = query.list();

                } catch (RuntimeException re) {
                    log.error("find by sql failed", re);
                    throw re;
                }
                return list;
            }
        });
    }

    /**
     * 根据sql查询,得到集合
     *
     * @param sql    sql语句
     * @param values 传过来的参数集合
     * @return
     * @throws Exception
     */
    public List findBySql(final String sql, final Object[] values) throws Exception {
        return getHibernateTemplate().executeFind(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                List list = null;
                try {
                    Query query = session.createSQLQuery(sql).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
                    //String sql = query.getQueryString();
                    if (values != null && values.length > 0) {
                        for (int i = 0; i < values.length; i++) {
                            query.setParameter(i, values[i]);
                        }
                    }
                    list = query.list();

                } catch (RuntimeException re) {
                    log.error("find by sql failed", re);
                    throw re;
                }
                return list;
            }
        });
    }


    /**
     * 根据SQL查询总数
     *
     * @param sql    sql语句
     * @param values 参数(无参数时可用null代替)
     * @return 返回一个int类型的总数
     * @throws Exception
     */
    public int countBySql(final String sql, final Object[] values) throws Exception {
        int count = 0;
        List list = getHibernateTemplate().executeFind(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                List list = null;
                try {
                    String sqlcount = "select count(1) COUNT from (" + sql + ")";
                    Query query = session.createSQLQuery(sqlcount).addScalar("COUNT", Hibernate.INTEGER);
                    if (values != null && values.length > 0) {
                        for (int i = 0; i < values.length; i++) {
                            query.setParameter(i, values[i]);
                        }
                    }
                    list = query.list();

                } catch (RuntimeException re) {
                    log.error("find by sql failed", re);
                    throw re;
                }
                return list;
            }
        });
        if (list != null) {
            count = (Integer) list.get(0);
        }
        return count;
    }

    /**
     * 根据SQL查询(可代?参数)
     *
     * @param sql       sql语句
     * @param values    Object数组型参数(如无参数请用null代替)
     * @param pageIndex 起始位置
     * @param pageMax   每页显示最大数
     * @return 返回一个包含Map(字段全大写)的List
     * @throws Exception
     */
    public List findBySql(final String sql, final Map<String, Object> values, final Integer pageIndex, final Integer pageMax)
            throws Exception {
        return getHibernateTemplate().executeFind(new HibernateCallback() {
            @Override
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                List list = null;
                try {
                    Query query = session.createSQLQuery(sql).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
                    query.getQueryString();
                    if (values != null) {

                        for (Map.Entry<String, Object> map : values.entrySet()) {

                            //这里考虑传入的参数是什么类型,不同类型使用的方法不同
                            if (map.getValue() instanceof Collection<?>) {
                                query.setParameterList(map.getKey(), (Collection<?>) map.getValue());
                            } else if (map.getValue() instanceof Object[]) {
                                query.setParameterList(map.getKey(), (Collection<?>) map.getValue());
                            } else {
                                query.setParameter(map.getKey(), map.getValue());
                            }
                        }
                    }
                    if (pageIndex != 0 && pageMax != 0) {
                        query.setFirstResult((pageIndex.intValue() - 1) * pageMax.intValue());
                        query.setMaxResults(pageMax);
                    }

                    list = query.list();

                } catch (RuntimeException re) {
                    log.error("find by sql failed", re);
                    throw re;
                }
                return list;
            }
        });
    }

    /**
     * 根据SQL查询总数
     *
     * @param sql    sql语句
     * @param values 参数(无参数时可用null代替)
     * @return 返回一个int类型的总数
     * @throws Exception
     */
    public int countBySql(final String sql, final Map<String, Object> values) throws Exception {
        int count = 0;
        List list = getHibernateTemplate().executeFind(new HibernateCallback() {
            @Override
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                List list = null;
                try {
                    String sqlcount = "select count(1) COUNT from (" + sql + ")";
                    Query query = session.createSQLQuery(sqlcount).addScalar("COUNT", Hibernate.INTEGER);
                    if (values != null) {

                        for (Map.Entry<String, Object> map : values.entrySet()) {

                            //这里考虑传入的参数是什么类型,不同类型使用的方法不同
                            if (map.getValue() instanceof Collection<?>) {
                                query.setParameterList(map.getKey(), (Collection<?>) map.getValue());
                            } else if (map.getValue() instanceof Object[]) {
                                query.setParameterList(map.getKey(), (Collection<?>) map.getValue());
                            } else {
                                query.setParameter(map.getKey(), map.getValue());
                            }
                        }
                    }
                    list = query.list();

                } catch (RuntimeException re) {
                    log.error("find by sql failed", re);
                    throw re;
                }
                return list;
            }
        });
        if (list != null) {
            count = (Integer) list.get(0);
        }
        return count;
    }

    /**
     * 根据SQL查询总数
     *
     * @param sql    sql语句
     * @param values 参数(无参数时可用null代替)
     * @return 返回一个int类型的总数
     * @throws Exception
     */
    public int countBySqlList(final String sql, final List values) throws Exception {
        int count = 0;
        List list = getHibernateTemplate().executeFind(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                List list = null;
                try {
                    String sqlcount = "select count(1) COUNT from (" + sql + ")";
                    Query query = session.createSQLQuery(sqlcount).addScalar("COUNT", Hibernate.INTEGER);
                    if (values != null && values.size() > 0) {
                        for (int i = 0; i < values.size(); i++) {
                            query.setParameter(i, values.get(i));
                        }
                    }
                    list = query.list();

                } catch (RuntimeException re) {
                    log.error("find by sql failed", re);
                    throw re;
                }
                return list;
            }
        });
        if (list != null) {
            count = (Integer) list.get(0);
        }
        return count;
    }

    //可以强制进行从内存到数据库的同步
    public void flush() {
        getHibernateTemplate().flush();
    }

    //可以强制清除Session缓存
    public void clear() {
        getHibernateTemplate().clear();
    }

    /**
     * 根据hql 查询List
     *
     * @param queryString 查询hql语句
     * @param valuesName  hql 中代替 ? 的变量名
     * @param values      hql 中变量的值
     * @return
     * @throws Exception
     */
    public List findByHql(final String queryString, final List<String> valuesName, final List<Object> values, final int pageIndex, final int pageMax) throws Exception {
        List returnList = getHibernateTemplate().executeFind(new HibernateCallback() {

            @Override
            public Object doInHibernate(Session session)
                    throws HibernateException, SQLException {
                Query query = session.createQuery(queryString);
                if (values != null && values.size() > 0) {
                    Object object = null;
                    for (int i = 0; i < values.size(); i++) {
                        object = values.get(i);
                        if (object.getClass().equals(ArrayList.class)) {
                            query.setParameterList(valuesName.get(i), (ArrayList) object);
                        } else if (object.getClass().equals(List.class)) {
                            query.setParameterList(valuesName.get(i), (List) object);
                        } else if (object.getClass().equals(Long[].class)) {
                            query.setParameterList(valuesName.get(i), (Long[]) object);
                        } else if (object.getClass().equals(String[].class)) {
                            query.setParameterList(valuesName.get(i), (String[]) object);
                        } else if (object.getClass().equals(Integer[].class)) {
                            query.setParameterList(valuesName.get(i), (Integer[]) object);
                        } else {
                            query.setParameter(valuesName.get(i), object);
                        }
                    }
                }
                if (pageIndex != 0 && pageMax != 0) {
                    query.setFirstResult((pageIndex - 1) * pageMax);
                    query.setMaxResults(pageMax);
                }
                return query.list();
            }

        });
        return returnList;
    }

    public long findCountByHql(final String queryString, final List<String> valuesName, final List<Object> values) throws Exception {
        Long count = 0l;
        List list = getHibernateTemplate().executeFind(new HibernateCallback() {

            @Override
            public Object doInHibernate(Session session)
                    throws HibernateException, SQLException {
                Query query = session.createQuery(queryString);
                if (values != null && values.size() > 0) {
                    Object object = null;
                    for (int i = 0; i < values.size(); i++) {
                        object = values.get(i);
                        if (object.getClass().equals(ArrayList.class)) {
                            query.setParameterList(valuesName.get(i), (ArrayList) object);
                        } else if (object.getClass().equals(List.class)) {
                            query.setParameterList(valuesName.get(i), (List) object);
                        } else if (object.getClass().equals(Long[].class)) {
                            query.setParameterList(valuesName.get(i), (Long[]) object);
                        } else if (object.getClass().equals(String[].class)) {
                            query.setParameterList(valuesName.get(i), (String[]) object);
                        } else if (object.getClass().equals(Integer[].class)) {
                            query.setParameterList(valuesName.get(i), (Integer[]) object);
                        } else {
                            query.setParameter(valuesName.get(i), object);
                        }
                    }
                }
                Long size = (Long) query.uniqueResult();

                List<Long> sizeList = new ArrayList<Long>();
                sizeList.add(size);
                return sizeList;
            }

        });
        if (list != null) {
            count = (Long) list.get(0);
        }
        return count;
    }

    /**
     * 执行sql语句
     *
     * @param tableName:Pojo类的类名,例如:Demo
     * @param condition:条件
     * @param value:属性值
     **/
    public void execBySql(String sql) {
        log.debug("exec by sql:" + sql);
        try {
            Session session = getSession();
            SQLQuery query = session.createSQLQuery(sql);
            query.executeUpdate();
            log.debug("exec successful");
        } catch (RuntimeException re) {
            log.error("exec failed", re);
            throw re;
        }
    }
}

EventService类


public class EventService extends BaseService {
    public void addOrUpdate(TUmEvent_ event){
        this.baseDao.saveOrUpdate(event);
    }
}

第三步

创建EventController类

@Slf4j
public class EventController extends BaseController {

    @Autowired
    private EventService eventService;

    /**
     * 添加或更新
     */
    @LogEventAnnotation(EventmenuName = "事件详情",uEventType = UEventType.SAVE,uEventName = "新增事件")
    public void addEvent(HttpServletRequest request, HttpServletResponse response, ShowUmEvent form) throws Exception{
        boolean flag = true;
        try{

            TUmEvent_ event_= new TUmEvent_();
            event_.setEventId((long)0);
            event_.setCreator((long)1);
            event_.setVersion(1);
            event_.setIsSCore(3);
            event_.setModifyTime(new Date());
            event_.setDefId(form.getDefId());
            event_.setEventCode(form.getEventCode());
            event_.setEventClass(form.getEventClass());
            event_.setEventDesc(form.getEventDesc());
            event_.setXzqyId(form.getXzqyId());
            event_.setStatus(form.getStatus());
            event_.setCreateTime(new Date());
            event_.setCurrentStepName(form.getCurrentStepName());
            event_.setCurrentDept(form.getCurrentDept());
            event_.setCurrentDealPeople(form.getCurrentDealPeople());


            eventService.addOrUpdate(event_);
            System.out.println("---form---: "+form);
            PrintWriter out=response.getWriter();
        }catch (Exception e){
            flag =false;
            e.printStackTrace();
        }
    }
}

第四步

打开postman测试

增加一个案件增加或修改的接口

测试

增加一个案件增加或修改的接口

添加sql语句

增加一个案件增加或修改的接口

修改sql语句

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://itzsg.com/37010.html

(0)

相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

联系我们YX

mu99908888

在线咨询: 微信交谈

邮件:itzsgw@126.com

工作时间:时刻准备着!

关注微信