Example usage for org.hibernate Session getSessionFactory

List of usage examples for org.hibernate Session getSessionFactory

Introduction

In this page you can find the example usage for org.hibernate Session getSessionFactory.

Prototype

SessionFactory getSessionFactory();

Source Link

Document

Get the session factory which created this session.

Usage

From source file:com.viettel.logistic.wms.service.StockImportServiceImpl.java

@Override
public ResultDTO synImportStockCust(StockTransDTO stockTransDTO) {
    //Do KPI/* ww w. ja  va  2  s  .c  o  m*/
    KpiLogDTO synKpiLog = new KpiLogDTO();
    String sStartTime = DateUtil.sysdateString();
    String functionCode;
    String reason;
    String strResult = "";
    String descr;
    String transactionCode = null;
    synKpiLog.setStartTime(sStartTime);
    synKpiLog.setCreateDatetime(sStartTime);
    //Ket thuc khoi tao doi tuong do kpi
    String stockTransDetailId;
    List<StockTransSerialDTO> filterListStockTransSerialDTO;
    String stockTransCode;
    String stockTransSEQ;
    ResultDTO resultDTO = new ResultDTO();
    resultDTO.setMessage(ParamUtils.SUCCESS);
    Map<String, GoodsDTO> mapGoodsDTO;

    int insertSuccess = 0;
    int insertFail = 0;
    Double amountIssue;
    //
    String stockTransId = "";
    String sysdate;
    //INIT TRANSACTION
    Session session;
    Transaction transaction;
    Connection connection = null;
    session = sessionFactory.openSession();
    transaction = session.getTransaction();
    transaction.begin();
    //
    sysdate = stockGoodsBusiness.getSysDate(formatDate);
    GoodsDTO goodsDTO;
    //du lieu cho dong bo bccs
    OrdersDTO ordersDTO = null;
    long startTime = System.currentTimeMillis();
    long time;
    //=====================================        
    List<StockTransDetailDTO> lstStockTransDetail = new ArrayList<>();
    List<StockTransDetailDTO> lstStockTransDetailDTOsImportAndUpdate = new ArrayList<>();
    //DUYOT: 27/01/2016: loc ra danh sach hang kit
    for (StockTransDetailDTO i : stockTransDTO.getLstStockTransDetailDTO()) {
        //Neu TH nhap kit --> se truyen vao transfersGoodsCode la code cua hang hoa sim--> Thuc hien xuat sim va nhap kit
        if (!DataUtil.isStringNullOrEmpty(i.getTransfersGoodsCode())) {
            lstStockTransDetailDTOsImportAndUpdate.add(i);
        } else {
            lstStockTransDetail.add(i);
        }
    }

    //DUYOT: 28/01/2016: check lai trang thai cua yeu cau - lenh---------------------
    //CHECK THONG TIN YEU CAU - LENH CO TRANG THAI HOP LE-------------------
    String orderIdList = stockTransDTO.getOrderIdList();
    if (orderIdList == null || orderIdList.equals("")) {
        resultDTO.setMessage(ParamUtils.FAIL);
        resultDTO.setKey(ParamUtils.ERROR_MESSAGE.ORDER_IE);
        return resultDTO;
    }
    try {
        ordersDTO = WSOrders.findOrderById(orderIdList);
    } catch (Exception ex) {
        Logger.getLogger(StockImportServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
    }
    if (ordersDTO != null && ORDER_STATUS_IMPORTED_EXPORTED.equalsIgnoreCase(ordersDTO.getOrderStatus())) {
        resultDTO.setMessage(ParamUtils.FAIL);
        resultDTO.setKey(ParamUtils.ERROR_MESSAGE.ORDER_IE);
        return resultDTO;
    }
    //---------------------------------------------------------------------------------
    //
    functionCode = "CREATE_BILL_IMPORT_LOG";
    if (ordersDTO != null) {
        transactionCode = ordersDTO.getOrderCode();
    }
    try {
        //-------------------------------------------------------------------  
        //1. KHOI TAO CONNECTION
        //-------------------------------------------------------------------    
        SessionFactory sessionFactoryBatch = session.getSessionFactory();
        connection = sessionFactoryBatch.getSessionFactoryOptions().getServiceRegistry()
                .getService(ConnectionProvider.class).getConnection();
        connection.setAutoCommit(false);
        //-------------------------------------------------------------------
        //THUC HIEN GIAO DICH THU HOI DOI VOI HANG KIT ( XUAT SIM -> NHAP KIT)-----------------
        if (!DataUtil.isListNullOrEmpty(lstStockTransDetailDTOsImportAndUpdate)) {
            System.out.println("LOG: BAT DAU THUC HIEN DONG BO NHAP KIT");
            StockTransDTO exportStockTransDTO = (StockTransDTO) DataUtil.cloneObject(stockTransDTO);
            exportStockTransDTO.setStockTransStatus(ParamUtils.TRANS_STATUS.WAITING_IMPORT);
            //duyot 27/01/2016
            //tao danh sach serial cho tat cat hang hoa -> loc sau
            List<StockTransSerialDTO> lstStockTransSerialDTO = new ArrayList<>();
            int countTemp = 0;
            for (StockTransDetailDTO i : lstStockTransDetailDTOsImportAndUpdate) {
                //set lai lst temp de filter
                String temp = countTemp + "";
                i.setTmpStockTransDetailId(temp);
                //
                List<StockTransSerialDTO> lstSerialInDetail = i.getLstStockTransSerialDTO();
                for (StockTransSerialDTO j : lstSerialInDetail) {
                    j.setTmpStockTransDetailId(temp);
                    lstStockTransSerialDTO.add(j);
                }
                //                    lstStockTransSerialDTO.addAll(lstSerialInDetail);
                countTemp++;
            }
            //
            exportStockTransDTO.setStockTransType("2");
            exportStockTransDTO.setStockTransId(null);
            //Lay danh sach goods code tu transfersGoodsCode
            String goodsCodeList = getGoodsCodeList(lstStockTransDetailDTOsImportAndUpdate);
            List<ConditionBean> lstConditionBean = new ArrayList<>();
            lstConditionBean.add(new ConditionBean("custId", ParamUtils.OP_EQUAL, stockTransDTO.getCustId(),
                    ParamUtils.TYPE_NUMBER));
            lstConditionBean
                    .add(new ConditionBean("code", ParamUtils.OP_IN, goodsCodeList, ParamUtils.TYPE_STRING));
            List<GoodsDTO> lstGoodsDTO = goodsBusiness.searchByConditionBean(lstConditionBean, 0,
                    Integer.MAX_VALUE, "", "code");
            //DAY VAO MAP DANH SACH HANG HOA
            Map<String, GoodsDTO> mapGoodsCode2DTO = DataUtil.putGoodsCodeToMap(lstGoodsDTO);
            ResultDTO result;
            // Map giua hang da xuat -> danh sach stock_goods cua hang do
            Map<String, List<StockGoods>> mapStockgoods = new HashMap<>();
            Map<String, List<StockGoodsSerialStrip>> mapSerialTrip = new HashMap<>();
            //Danh sach sim trang se xuat kho
            List<StockTransDetailDTO> lstExportDetail = DataUtil
                    .cloneList(lstStockTransDetailDTOsImportAndUpdate);
            GoodsDTO goods;
            for (StockTransDetailDTO o : lstExportDetail) {
                goods = mapGoodsCode2DTO.get(o.getTransfersGoodsCode());
                o.setGoodsCode(goods.getCode());
                o.setGoodsId(goods.getGoodsId());
                o.setGoodsName(goods.getName());
            }
            //1--> BEGIN TRANS
            /*
            - khi da xuat hang -> dua ra map hang da ban cho phan nhap
            */
            //-->2 THUC HIEN GIAO DICH XUAT MAT HANG SIM TRANG
            result = exportStockGoodsTransfer(exportStockTransDTO, lstExportDetail,
                    DataUtil.cloneList(lstStockTransSerialDTO), session, transaction, mapStockgoods,
                    mapSerialTrip);
            if (!result.getMessage().equals(ParamUtils.SUCCESS)) {
                return result;
            }
            //-->3 THUC HIEN GIAO DICH NHAP KIT DUOC XUAT TU SIM TRANG
            //1. Cap nhat vao transaction
            //set fromstocktransid
            stockTransDTO.setFromStockTransId(result.getId());
            //
            List<GoodsInTicketDTO> lstGoods = new ArrayList<>();
            stockTransDTO.setStockTransStatus(ParamUtils.TRANS_STATUS.WAITING_IMPORT);
            result = importStockGoodsTransfer(stockTransDTO, lstStockTransDetailDTOsImportAndUpdate,
                    lstExportDetail, DataUtil.cloneList(lstStockTransSerialDTO),
                    DataUtil.cloneList(lstStockTransSerialDTO), session, transaction, mapStockgoods,
                    mapSerialTrip, lstGoods);
            if (!result.getMessage().equals(ParamUtils.SUCCESS)) {
                return result;
            }
            stockTransId = result.getId();
        }
        //END QUYENDM: KET THUC NHAP KIT-------------------------------------------------------------
        //Ghi log ra file KPI        
        String synSys = Constants.TYPE_ORDERS_BCCS.equalsIgnoreCase(ordersDTO.getSourceOrder()) ? "BCCS"
                : "KTTS";
        String description = "Viet phieu nhap dong bo " + synSys + "| YC: " + orderIdList;
        System.out.println(DateUtil.sysdateString() + " | " + description);
        //DOI VOI HANG HOA KHONG PHAI LA HANG KIT---------------------------------------------------
        if (!DataUtil.isListNullOrEmpty(lstStockTransDetail)) {
            //Kiem tra xem giao dich nhap thu hoi hay nhap moi
            if (ordersDTO.getInputType() != null && !ordersDTO.getInputType().equalsIgnoreCase("1")) {
                //Begin - ThienNG1 - NEU LA GIAO DICH THU HOI
                //                    resultDTO = reSyncImportRecovered(stockTransDTO, Constants.STATUS_SERIAL_WAIT_STOCK, session, transaction);
                //Begin - QuyenDM 20160413 - VIET LAI GIAO DICH THU HOI
                //----------------------------------------
                //1. KHOI TAO CONNECTION                    
                resultDTO = reSyncImportRecovered(stockTransDTO, Constants.STATUS_SERIAL_WAIT_STOCK, connection,
                        session);
                if (!resultDTO.getMessage().equalsIgnoreCase(ParamUtils.SUCCESS)) {
                    rollback(session, transaction, connection);
                    return resultDTO;
                }

                //End - QuyenDM 20160413 - VIET LAI GIAO DICH THU HOI
            } else {
                //NEU LA NHAP HANG BT
                //INSERT GIAO DICH STOCK_TRANS
                stockTransSEQ = stockTransBusiness.getSequence("STOCK_TRANS_SEQ");
                stockTransCode = ParamUtils.CODE_IMPORT_STOCK + stockTransSEQ;
                stockTransDTO.setStockTransCode(stockTransCode);
                stockTransDTO.setCreateDatetime(sysdate);
                stockTransDTO.setStockTransDate(sysdate);
                stockTransDTO.setStockTransId(stockTransSEQ);
                //                    resultDTO = stockTransBusiness.createObjectSession(stockTransDTO, session);
                resultDTO = commonBusinessInterface.insertStockTrans(stockTransDTO, connection);

                stockTransId = stockTransDTO.getStockTransId();
                stockTransDTO.setStockTransId(stockTransId);
                if (!resultDTO.getMessage().equals(ParamUtils.SUCCESS)) {
                    rollback(session, transaction, connection);
                    return resultDTO;
                }
                //DAY VAO MAP DANH SACH HANG HOA
                String goodsIdList = getGoodsIdList(lstStockTransDetail);
                List<ConditionBean> lstConditionBean = new ArrayList<>();
                lstConditionBean.add(new ConditionBean("custId", ParamUtils.OP_EQUAL, stockTransDTO.getCustId(),
                        ParamUtils.TYPE_NUMBER));
                lstConditionBean.add(
                        new ConditionBean("goodsId", ParamUtils.OP_IN, goodsIdList, ParamUtils.TYPE_NUMBER));
                List<GoodsDTO> lstGoodsDTO = goodsBusiness.searchByConditionBean(lstConditionBean, 0,
                        Integer.MAX_VALUE, "", "code");
                mapGoodsDTO = DataUtil.putGoodsToMap(lstGoodsDTO);
                //LOOP: CHI TIET CHO TUNG MAT HANG
                for (StockTransDetailDTO stockTransDetailDTO : lstStockTransDetail) {
                    //lay seq
                    String stockTransDetailSEQ = stockTransDetailBusiness.getSequence("STOCK_TRANS_DETAIL_SEQ");
                    stockTransDetailDTO.setStockTransId(stockTransId);
                    stockTransDetailDTO.setStockTransDetailId(stockTransDetailSEQ);
                    stockTransDetailDTO.setStockTransDate(sysdate);
                    stockTransDetailDTO.setCreateDatetime(sysdate);
                    goodsDTO = mapGoodsDTO.get(stockTransDetailDTO.getGoodsId());
                    if (goodsDTO == null) {
                        rollback(session, transaction, connection);
                        resultDTO.setMessage(ParamUtils.GOODS_IS_NOT_EXIST);
                        resultDTO.setKey(ParamUtils.GOODS_IS_NOT_EXIST);
                        return resultDTO;
                    }
                    //INSERT CHI TIET GIAO DICH KHO STOCK_TRANS_DETAIL
                    stockTransDetailDTO.setGoodsCode(goodsDTO.getCode());
                    stockTransDetailDTO.setGoodsName(goodsDTO.getName());
                    stockTransDetailDTO.setGoodsIsSerial(goodsDTO.getIsSerial());
                    stockTransDetailDTO.setGoodsIsSerialStrip(goodsDTO.getIsSerialStrip());
                    //------
                    resultDTO = commonBusinessInterface.insertStockTransDetail(stockTransDetailDTO, connection);
                    //-------------
                    stockTransDetailDTO.setStockTransDetailId(stockTransDetailSEQ);
                    stockTransDetailId = stockTransDetailSEQ;
                    //
                    if (!resultDTO.getMessage().equals(ParamUtils.SUCCESS)) {
                        rollback(session, transaction, connection);
                        resultDTO.setMessage(Constants.ERROR_MESSAGE.INSERT_STOCK_TRANS_DETAIL_ERROR);
                        resultDTO.setKey(Constants.ERROR_MESSAGE.INSERT_STOCK_TRANS_DETAIL_ERROR);
                        return resultDTO;
                    }
                    //MAT HANG K THEO SERIAL
                    if (!stockTransDetailDTO.getGoodsIsSerial().equals(Constants.IS_SERIAL)) {
                        //Cap nhat mat hang theo so luong STOCK_GOODS
                        resultDTO = importStockGoods(stockTransDTO, stockTransDetailDTO, session,
                                ParamUtils.GOODS_IMPORT_STATUS.WAITING_IMPORT);
                        if (!resultDTO.getMessage().equals(ParamUtils.SUCCESS)) {
                            rollback(session, transaction, connection);
                            return resultDTO;
                        }
                    } else //MAT HANG QUAN LY THEO SERIAL
                    {
                        //LAY RA DANH SACH SERIAL CUA HANG HOA TUONG UNG
                        filterListStockTransSerialDTO = stockTransDetailDTO.getLstStockTransSerialDTO();
                        if (filterListStockTransSerialDTO == null || filterListStockTransSerialDTO.size() < 1) {
                            resultDTO.setMessage(ParamUtils.FAIL);
                            resultDTO.setKey(ParamUtils.SYSTEM_OR_DATA_ERROR);
                            rollback(session, transaction, connection);
                            return resultDTO;
                        }
                        //Insert giao dich chi tiet serial
                        amountIssue = 0D;
                        //khoi tao list serial duoc nhap kho cho mat hang nay
                        for (StockTransSerialDTO stockTransSerialDTO : filterListStockTransSerialDTO) {
                            //Cap nhat Id giao dich, ID chi tiet giao dichj
                            stockTransSerialDTO.setStockTransId(stockTransId);
                            stockTransSerialDTO.setStockTransDetailId(stockTransDetailId);
                            stockTransSerialDTO.setStockTransDate(sysdate);
                            stockTransSerialDTO.setCreateDatetime(sysdate);
                            stockTransSerialDTO.setGoodsCode(goodsDTO.getCode());
                            stockTransSerialDTO.setGoodsName(goodsDTO.getName());
                        }
                        //Insert batch VAO KHO STOCK_GOODS_SERIAL
                        resultDTO = importStockGoodsListSerial(stockTransDTO, stockTransDetailDTO,
                                filterListStockTransSerialDTO, session, connection,
                                ParamUtils.GOODS_IMPORT_STATUS.WAITING_IMPORT);
                        insertSuccess = insertSuccess + resultDTO.getQuantitySucc();
                        insertFail = insertFail + resultDTO.getQuantityFail();
                        amountIssue = resultDTO.getAmountIssue();
                        //

                        if (!resultDTO.getMessage().equals(ParamUtils.SUCCESS)) {
                            rollback(session, transaction, connection);
                            return resultDTO;
                        }
                        //KIEM TRA SO LUONG UPDATE SERIAL -> NEU CO LOI -> DAU RA THONG BAO
                        if (insertFail > 0) {
                            resultDTO.setQuantitySucc(insertSuccess);
                            resultDTO.setQuantityFail(insertFail);
                            resultDTO.setId(stockTransId);
                            resultDTO.setMessage(Constants.ERROR_MESSAGE.IS_OVERLAP);
                            rollback(session, transaction, connection);
                            return resultDTO;
                        }
                        //END FOR FILTER LIST
                        //CAP NHAT LAI STOCK_TRANS_DETAIL VOI SO LUONG INSERT THANH CONG
                        stockTransDetailDTO.setAmountReal(amountIssue.toString().replace(".0", ""));
                        int isUpdate = stockGoodsSerialBusiness2.updateStockTransDetail(stockTransDetailId,
                                amountIssue, connection);
                        //neu update khong thanh cong
                        if (isUpdate < 1) {
                            resultDTO.setMessage(ParamUtils.FAIL);
                            resultDTO.setKey("UPDATE_STOCK_TRANS_DETAIL_ERROR");
                            rollback(session, transaction, connection);
                            return resultDTO;
                        }
                    }
                } //KET THUC NHAP HANG BT
                  //
            } //KET THUC NHHAP K PHAI KIT
        }
        //DUYOT: KET THUC: GOI HAM DONG BO--------------------------------------
        /*
             duyot: dong bo sang bccs: gui thong tin thuc nhap
             1. lay ra thong tin nhap kho theo format: billstock-listgoods-list serial
             2. goi sang service bccs
             3. check ket qua tra ve
             */
        resultDTO = getListOrdersTicket(stockTransDTO, ordersDTO, connection, session);
        if (!ParamUtils.SUCCESS.equals(resultDTO.getMessage())) {
            rollback(session, transaction, connection);
            //                    resultDTO.setMessage(ParamUtils.FAIL);
            resultDTO.setKey(ParamUtils.ERROR_MESSAGE.SYNC_FAIL);
            return resultDTO;
        }
        //neu hoan toan k co loi -> commit
        commit(session, transaction, connection);

    } catch (Exception e) {
        rollback(session, transaction, connection);
        Logger.getLogger(StockImportServiceImpl.class.getName()).log(Level.SEVERE, null, e);
        resultDTO.setMessage(e.getMessage());
        resultDTO.setKey(ParamUtils.SYSTEM_OR_DATA_ERROR);
        return resultDTO;
    } finally {
        time = System.currentTimeMillis() - startTime;
        //Ghi ra file KPI.log
        if (resultDTO.getMessage() != null) {
            strResult = resultDTO.getMessage().equalsIgnoreCase(null) ? resultDTO.getKey()
                    : resultDTO.getMessage();
        }
        //Ghi ra file Catalina.out  
        //Ghi log ra file KPI        
        synKpiLog.setFunctionCode(functionCode);
        synKpiLog.setTransactionCode(transactionCode);
        descr = "Tong thoi gian viet phieu nhap " + transactionCode + " : " + time;
        System.out.println(descr);
        KPILogger.createLogs(descr);
        if (!strResult.equalsIgnoreCase(ParamUtils.SUCCESS)) {
            reason = resultDTO.getMessage();
            synKpiLog.setReason(reason);
            synKpiLog.setStockTransStatus(SYN_FAIL);
        } else {
            synKpiLog.setStockTransStatus(SYN_SUCC);
        }
        synKpiLog.setEndTime(DateUtil.sysdateString());
        synKpiLog.setDuration(String.valueOf(time));
        synKpiLog.setDescription("Tao phieu nhap dong bo tren HT LOG");
        //Ghi ra bang kpi_log
        kpiLogBusiness.createKpiLog(synKpiLog);
        try {
            if (session.isOpen()) {
                session.close();
            }
            if (connection != null && !connection.isClosed()) {
                connection.close();
            }
        } catch (SQLException ex) {
            Logger.getLogger(StockImportServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    //
    resultDTO.setQuantitySucc(insertSuccess);
    resultDTO.setQuantityFail(insertFail);
    resultDTO.setId(stockTransId);

    return resultDTO;

}

From source file:com.viettel.logistic.wms.service.StockTransServiceImpl.java

License:Open Source License

@Override
public Boolean inventoryInStock(List<StockTransDTO> lstStockTrans, CustomerDTO customer, StockDTO stock) {
    SYS_DATE = stockTransBusiness.getSysDate(FORMAT_DATE);
    Session session;
    Connection connection = null;
    Transaction transaction = null;/*from w  ww .  j  a  va 2 s. co m*/
    session = sessionFactory.openSession();
    SessionFactory sessionFactoryBatch = session.getSessionFactory();
    StockTransDTO tempStockTrans;
    String oldStockTranId;
    for (StockTransDTO stockTrans : lstStockTrans) {
        //Thuc hien them moi stockTrans
        oldStockTranId = stockTrans.getStockTransId();
        //Neu la giao dich nhap thuc hien tao moi connection
        if ("1".equalsIgnoreCase(stockTrans.getStockTransType())) {
            tempStockTrans = initNewStockTransDTO(customer, stock, stockTrans, true);
            inventoryImportTransaction(session, connection, sessionFactoryBatch, tempStockTrans,
                    oldStockTranId);
        } else if ("2".equalsIgnoreCase(stockTrans.getStockTransType())) {
            tempStockTrans = initNewStockTransDTO(customer, stock, stockTrans, false);
            inventoryExportTransaction(session, transaction, tempStockTrans, oldStockTranId);
        }
    }
    if (session.isOpen()) {
        session.close();
    }
    return Boolean.TRUE;
}

From source file:com.xumpy.security.root.InitOldDatabase.java

@Bean
public SessionFactory sessionFactory() {
    Session session = (Session) entityManagerFactory.getObject().createEntityManager().getDelegate();

    log.info(entityManagerFactory.nativeEntityManagerFactory);

    return session.getSessionFactory();
}

From source file:corner.orm.tapestry.table.RelativePersistentBasicTableModel.java

License:Apache License

private Query createQuery(Session session, Collection c, String selectStr, String orderStr) {
    //TODO ?/* w  w w . j  a v  a  2 s. c o m*/

    StringBuffer sb = new StringBuffer();
    if (selectStr != null) {
        sb.append(selectStr).append(" ");
    }

    Query query;
    if (callback != null) {
        //========  Example?.
        Criteria criteria = callback.createCriteria(session);

        //?
        callback.appendCriteria(criteria);
        String rootEntityName = ((CriteriaImpl) criteria).getEntityOrClassName();
        CriteriaQueryTranslator criteriaQuery = new CriteriaQueryTranslator(
                (SessionFactoryImplementor) session.getSessionFactory(), (CriteriaImpl) criteria,
                rootEntityName, Criteria.ROOT_ALIAS);
        String where = criteriaQuery.getWhereCondition();
        QueryParameters qps = criteriaQuery.getQueryParameters();

        //Criteria??where??
        if (where != null && where.length() > 0) {
            sb.append("where ").append(where).append(" ");
        }
        if (orderStr != null) {
            sb.append(orderStr);
        }
        query = session.createFilter(c, sb.toString()).setParameters(qps.getPositionalParameterValues(),
                qps.getPositionalParameterTypes());
    } else {
        if (orderStr != null) {
            sb.append(orderStr);
        }
        query = session.createFilter(c, sb.toString());

    }

    return query;

}

From source file:corner.service.EntityService.java

License:Apache License

/**
 * ?persist?//from  www  .  j av a 2  s  .c  om
 * 
 * @param entity
 *            ?
 * @return ??
 * @since 2.0.3
 */
public boolean isPersistent(final Object entity) {
    if (entity == null) {
        return false;
    }
    return ((Boolean) ((HibernateObjectRelativeUtils) getObjectRelativeUtils()).getHibernateTemplate()
            .execute(new HibernateCallback() {

                public Object doInHibernate(Session session) throws HibernateException, SQLException {
                    final ClassMetadata classMetadata = session.getSessionFactory()
                            .getClassMetadata(getEntityClass(entity));
                    return classMetadata != null
                            && classMetadata.getIdentifier(entity, EntityMode.POJO) != null;

                }
            })).booleanValue();
}

From source file:corner.services.impl.EntityServiceImpl.java

License:Apache License

public EntityServiceImpl(final Session session, final TypeCoercer typeCoercer) {
    this.template = new HibernateTemplate() {
        /**//from   w w w  .  j  ava 2  s  .c o  m
         * @see org.springframework.orm.hibernate3.HibernateTemplate#execute(org.springframework.orm.hibernate3.HibernateCallback, boolean)
         */
        @Override
        public Object doExecute(HibernateCallback action, boolean enforceNewSession,
                boolean enforceNativeSessio) throws DataAccessException {
            try {
                return action.doInHibernate(session);
            } catch (HibernateException ex) {
                throw convertHibernateAccessException(ex);
            } catch (SQLException ex) {
                throw convertJdbcAccessException(ex);
            }
        }
    };
    this.sessionFactory = session.getSessionFactory();
    this.paginatedService = new PaginatedEntityService(template, typeCoercer);
}

From source file:de.iteratec.iteraplan.persistence.util.SqlHqlStringUtils.java

License:Open Source License

public static String escapeSqlLikeOperatorWildcards(String filter, Session session) {
    // using | as escape sequence:
    // replace | with ||
    String res = filter;/*from w w  w. j  av  a 2 s.  co m*/
    Character escapeChar = Constants.SQL_LIKE_OPERATOR_ESCAPE_CHAR;
    res = res.replaceAll("\\" + escapeChar, "\\" + escapeChar + "\\" + escapeChar);
    // replace % with |%
    res = res.replaceAll("%", escapeChar + "%");
    // replace _ with |_
    res = res.replaceAll("_", escapeChar + "_");

    if (session != null && session.getSessionFactory() instanceof SessionFactoryImplementor) {
        res = escapeSqlLikeSquareBrackets(res,
                ((SessionFactoryImplementor) session.getSessionFactory()).getDialect());
    }
    return res;
}

From source file:de.iteratec.iteraplan.persistence.util.SqlHqlStringUtils.java

License:Open Source License

/**
 * unlike other DBMS, SQL Server's LIKE operator treats '[', ']' as special characters.
 * /*  www  . j ava 2 s .com*/
 * @param session current hibernate session (used to check if we query an mssql server)
 * @param filter the filter string to escape [ and ] within
 * @return the filter with [ and ] escaped
 */
public static String escapeSqlLikeSquareBrackets(String filter, Session session) {
    String res = filter;

    if (session != null && session.getSessionFactory() instanceof SessionFactoryImplementor) {
        res = escapeSqlLikeSquareBrackets(res,
                ((SessionFactoryImplementor) session.getSessionFactory()).getDialect());
    }

    return res;
}

From source file:debop4k.data.orm.hibernate.StatelessEx.java

License:Apache License

public static StatelessSessionImpl of(@NonNull Session session) {
    return of(session.getSessionFactory());
}

From source file:edu.sjsu.cmpe275.lab2.model.HibernateUtil.java

License:Open Source License

public static void main(final String[] args) throws Exception {
    Session session = getSessionFactory().openSession();

    try {/*from www .  java 2  s  .com*/
        System.out.println("querying all the managed entities...");
        final Map metadataMap = session.getSessionFactory().getAllClassMetadata();
        for (Object key : metadataMap.keySet()) {
            final ClassMetadata classMetadata = (ClassMetadata) metadataMap.get(key);
            final String entityName = classMetadata.getEntityName();
            final Query query = session.createQuery("from " + entityName);
            System.out.println("executing: " + query.getQueryString());
            for (Object o : query.list()) {
                System.out.println("  " + o);
            }
        }
    } finally {
        session.close();
    }
}