@Override public Map<String, Object> saveMap(Map<String, Object> object, Class clazz) throws Exception { StringBuilder sql = new StringBuilder(); EntityInfo entityInfo = ClassUtils.getEntityInfoByClazz(clazz); sql.append("INSERT INTO "); sql.append(entityInfo.getTableName()); sql.append("("); List<String> columns = new ArrayList<String>(); List<Object> values = new ArrayList<Object>(); Map<String, String> ptcMap = ClassUtils.propToColumnMap.get(entityInfo.getClazzName()); for (Map.Entry<String, Object> entry : object.entrySet()) { columns.add(ptcMap.get(entry.getKey())); values.add(entry.getValue()); } sql.append(StringUtils.join(columns, ",")); sql.append(") VALUES("); String[] params = new String[values.size()]; Arrays.fill(params, "?"); sql.append(StringUtils.join(params, ",")); sql.append(")"); if (entityInfo.getStrategy().equals(GenerationType.IDENTITY)) { Long id = addReutrnId(sql.toString(), values); if (id != null) { object.put(entityInfo.getPkName(), id); } } else { add(sql.toString(), values); } return object; }
/* * Returns list of sensors currently loaded in the system * */ public static String getListOfSensors() { StringBuilder s = new StringBuilder(); Iterator iter = Mappings.getAllVSensorConfigs(); sensors.clear(); coordinates.clear(); while (iter.hasNext()) { VSensorConfig sensorConfig = (VSensorConfig) iter.next(); Double longitude = sensorConfig.getLongitude(); Double latitude = sensorConfig.getLatitude(); Double altitude = sensorConfig.getAltitude(); String sensor = sensorConfig.getName(); if ((latitude != null) && (longitude != null) && (altitude != null)) { Point point = new Point(latitude, longitude, altitude); coordinates.add(point); sensors.add(sensor); s.append(sensor) .append(" => ") .append(longitude) .append(" : ") .append(latitude) .append("\n"); } } return s.toString(); }
/** Returns a connection to the database */ public synchronized Connection get() throws DataException { // ensure we haven't used too many connections if (usedConnections.size() >= MAX_CONNECTIONS) { throw new DataException( "The database connection pool is out of connections -- a maximum number of " + MAX_CONNECTIONS); } // if try { // do we have enough connections to assign one out? if (freeConnections.size() == 0) { freeConnections.add(createConnection()); } // return the first free connection Connection conn = freeConnections.remove(0); usedConnections.add(conn); // Logger.global.info("Gave out a connection from the pool. Free size is now: " + // freeConnections.size() + "/" + (freeConnections.size() + usedConnections.size())); return conn; } catch (Exception e) { throw new DataException( "An error occurred while retrieving a database connection from the pool", e); } } // get
public CFSecuritySecDeviceBuff[] readBuffByUserIdx( CFSecurityAuthorization Authorization, UUID SecUserId) { final String S_ProcName = "readBuffByUserIdx"; ResultSet resultSet = null; try { Connection cnx = schema.getCnx(); String sql = "call " + schema.getLowerDbSchemaName() + ".sp_read_secdev_by_useridx( ?, ?, ?, ?, ?" + ", " + "?" + " )"; if (stmtReadBuffByUserIdx == null) { stmtReadBuffByUserIdx = cnx.prepareStatement(sql); } int argIdx = 1; stmtReadBuffByUserIdx.setLong( argIdx++, (Authorization == null) ? 0 : Authorization.getSecClusterId()); stmtReadBuffByUserIdx.setString( argIdx++, (Authorization == null) ? "" : Authorization.getSecUserId().toString()); stmtReadBuffByUserIdx.setString( argIdx++, (Authorization == null) ? "" : Authorization.getSecSessionId().toString()); stmtReadBuffByUserIdx.setLong( argIdx++, (Authorization == null) ? 0 : Authorization.getSecClusterId()); stmtReadBuffByUserIdx.setLong( argIdx++, (Authorization == null) ? 0 : Authorization.getSecTenantId()); stmtReadBuffByUserIdx.setString(argIdx++, SecUserId.toString()); try { resultSet = stmtReadBuffByUserIdx.executeQuery(); } catch (SQLException e) { if (e.getErrorCode() != 1329) { throw e; } resultSet = null; } List<CFSecuritySecDeviceBuff> buffList = new LinkedList<CFSecuritySecDeviceBuff>(); while ((resultSet != null) && resultSet.next()) { CFSecuritySecDeviceBuff buff = unpackSecDeviceResultSetToBuff(resultSet); buffList.add(buff); } int idx = 0; CFSecuritySecDeviceBuff[] retBuff = new CFSecuritySecDeviceBuff[buffList.size()]; Iterator<CFSecuritySecDeviceBuff> iter = buffList.iterator(); while (iter.hasNext()) { retBuff[idx++] = iter.next(); } return (retBuff); } catch (SQLException e) { throw CFLib.getDefaultExceptionFactory().newDbException(getClass(), S_ProcName, e); } finally { if (resultSet != null) { try { resultSet.close(); } catch (SQLException e) { } resultSet = null; } } }
public List<PromoterRowGateway> findAll() { List result = new ArrayList(); List promoters = jdbcTemplate.queryForList(findAllStatement); for (int i = 0; i < promoters.size(); i++) result.add(PromoterRowGateway.load(dataSource, (Map) promoters.get(i))); return result; }
public ListIterator<ICFLibAnyObj> enumerateDetails(MssCFGenContext genContext) { final String S_ProcName = "CFAsteriskMssCFIterateHostNodeConfFile.enumerateDetails() "; if (genContext == null) { throw CFLib.getDefaultExceptionFactory() .newNullArgumentException(getClass(), S_ProcName, 1, "genContext"); } ICFLibAnyObj genDef = genContext.getGenDef(); if (genDef == null) { throw CFLib.getDefaultExceptionFactory() .newNullArgumentException(getClass(), S_ProcName, 1, "genContext.getGenDef()"); } List<ICFLibAnyObj> list = new LinkedList<ICFLibAnyObj>(); if (genDef instanceof ICFAsteriskHostNodeObj) { Iterator<ICFAsteriskConfigurationFileObj> elements = ((ICFAsteriskHostNodeObj) genDef).getOptionalComponentsConfFile().iterator(); while (elements.hasNext()) { list.add(elements.next()); } } else { throw CFLib.getDefaultExceptionFactory() .newUnsupportedClassException( getClass(), S_ProcName, "genContext.getGenDef()", genDef, "ICFAsteriskHostNodeObj"); } return (list.listIterator()); }
public void deleteTaxByTenantIdx(long TenantId) { CFAccTaxByTenantIdxKey key = ((ICFAccSchema) schema.getBackingStore()).getFactoryTax().newTenantIdxKey(); key.setRequiredTenantId(TenantId); if (indexByTenantIdx == null) { indexByTenantIdx = new HashMap<CFAccTaxByTenantIdxKey, Map<CFAccTaxPKey, ICFAccTaxObj>>(); } if (indexByTenantIdx.containsKey(key)) { Map<CFAccTaxPKey, ICFAccTaxObj> dict = indexByTenantIdx.get(key); ((ICFAccSchema) schema.getBackingStore()) .getTableTax() .deleteTaxByTenantIdx(schema.getAuthorization(), TenantId); Iterator<ICFAccTaxObj> iter = dict.values().iterator(); ICFAccTaxObj obj; List<ICFAccTaxObj> toForget = new LinkedList<ICFAccTaxObj>(); while (iter.hasNext()) { obj = iter.next(); toForget.add(obj); } iter = toForget.iterator(); while (iter.hasNext()) { obj = iter.next(); obj.forget(true); } indexByTenantIdx.remove(key); } else { ((ICFAccSchema) schema.getBackingStore()) .getTableTax() .deleteTaxByTenantIdx(schema.getAuthorization(), TenantId); } }
/** * Find the periods in a calendar year it need not be a standard period (used in MRP) * * @param C_Year_ID Year * @param periodType Period Type * @param ctx context * @param trx trx * @return MPeriod[] */ public static MPeriod[] getAllPeriodsInYear(int C_Year_ID, String periodType, Ctx ctx, Trx trx) { List<MPeriod> periods = new ArrayList<MPeriod>(); String sql = "SELECT * FROM C_Period WHERE IsActive='Y'"; sql = sql + " AND C_Year_ID = ?"; if (periodType != null) sql = sql + " AND PeriodType = ? "; sql = sql + " order by StartDate "; PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement(sql, trx); pstmt.setInt(1, C_Year_ID); if (periodType != null) pstmt.setString(2, periodType); rs = pstmt.executeQuery(); while (rs.next()) periods.add(new MPeriod(ctx, rs, trx)); } catch (Exception e) { s_log.log(Level.SEVERE, sql, e); } finally { DB.closeResultSet(rs); DB.closeStatement(pstmt); } MPeriod[] retValue = new MPeriod[periods.size()]; periods.toArray(retValue); return retValue; }
public void deleteSecDeviceByUserIdx(UUID SecUserId) { CFSecuritySecDeviceByUserIdxKey key = ((ICFSecuritySchema) schema.getBackingStore()).getFactorySecDevice().newUserIdxKey(); key.setRequiredSecUserId(SecUserId); if (indexByUserIdx == null) { indexByUserIdx = new HashMap< CFSecuritySecDeviceByUserIdxKey, Map<CFSecuritySecDevicePKey, ICFSecuritySecDeviceObj>>(); } if (indexByUserIdx.containsKey(key)) { Map<CFSecuritySecDevicePKey, ICFSecuritySecDeviceObj> dict = indexByUserIdx.get(key); ((ICFSecuritySchema) schema.getBackingStore()) .getTableSecDevice() .deleteSecDeviceByUserIdx(schema.getAuthorization(), SecUserId); Iterator<ICFSecuritySecDeviceObj> iter = dict.values().iterator(); ICFSecuritySecDeviceObj obj; List<ICFSecuritySecDeviceObj> toForget = new LinkedList<ICFSecuritySecDeviceObj>(); while (iter.hasNext()) { obj = iter.next(); toForget.add(obj); } iter = toForget.iterator(); while (iter.hasNext()) { obj = iter.next(); obj.forget(true); } indexByUserIdx.remove(key); } else { ((ICFSecuritySchema) schema.getBackingStore()) .getTableSecDevice() .deleteSecDeviceByUserIdx(schema.getAuthorization(), SecUserId); } }
private BibTrees fetchResultSet(int batchSize, BatchStatistics batchStatistics, Boolean isBibOnly) throws Exception { StopWatch stopWatch = new StopWatch(); stopWatch.start(); BibTrees bibTrees = new BibTrees(); int count = 0; if (batchSize <= 0) { return bibTrees; } while (bibResultSet.next()) { count++; BibTree bibTree = new BibTree(); Bib bib = fetchBibRecord(); bibTree.setBib(bib); if (!isBibOnly) { List<HoldingsTree> holdingsList = fetchHoldingsTreeForBib(Integer.parseInt(bib.getLocalId())); bibTree.getHoldingsTrees().addAll(holdingsList); batchStatistics.addHoldingsCount(holdingsList.size()); for (HoldingsTree holdingsTree : holdingsList) { batchStatistics.addItemCount(holdingsTree.getItems().size()); } } bibTrees.getBibTrees().add(bibTree); if (count == batchSize) { break; } } stopWatch.stop(); batchStatistics.addTimeTaken(stopWatch.getTotalTimeMillis()); batchStatistics.addBibCount(bibTrees.getBibTrees().size()); return bibTrees; }
@Test public void testJodaTime() { sql2o .createQuery("create table testjoda(id int primary key, joda1 datetime, joda2 datetime)") .executeUpdate(); sql2o .createQuery("insert into testjoda(id, joda1, joda2) values(:id, :joda1, :joda2)") .addParameter("id", 1) .addParameter("joda1", new DateTime()) .addParameter("joda2", new DateTime().plusDays(-1)) .addToBatch() .addParameter("id", 2) .addParameter("joda1", new DateTime().plusYears(1)) .addParameter("joda2", new DateTime().plusDays(-2)) .addToBatch() .addParameter("id", 3) .addParameter("joda1", new DateTime().plusYears(2)) .addParameter("joda2", new DateTime().plusDays(-3)) .addToBatch() .executeBatch(); List<JodaEntity> list = sql2o.createQuery("select * from testjoda").executeAndFetch(JodaEntity.class); assertTrue(list.size() == 3); assertTrue(list.get(0).getJoda2().isBeforeNow()); }
public static ArrayList getFjList(String sid) { ArrayList result = new ArrayList(); String strSql = "select SID,File_Name,Ext_Name,File_Size from t_docs_fj where state='1' and parent_sid=" + sid; CommonDao dao = CommonDao.GetOldDatabaseDao(); List lst = dao.fetchAll(strSql); if (lst != null && lst.size() > 0) { for (int i = 0; i < lst.size(); i++) { Object[] arr = (Object[]) lst.get(i); result.add(arr[1]); result.add(arr[2]); if (arr[3] != null) { Float fileSize = Float.parseFloat(arr[3].toString()) * 1000; result.add(fileSize); } else { result.add(0); } result.add(arr[0]); } } dao.getSessionFactory().close(); return result; /*Connection conn = null; Statement stmt = null; ResultSet rs = null; ArrayList result = new ArrayList(); String strSql = "select * from t_docs_fj where state='1' and parent_sid=" + sid; try { conn = DataManager.getConnection(); stmt = conn.createStatement(); rs = stmt.executeQuery(strSql); while (rs.next()) { result.add(rs.getString("File_Name")); result.add(rs.getString("Ext_Name")); result.add("" + Float.valueOf(rs.getString("File_Size")).floatValue() * 1000.0); result.add(rs.getString("SID")); result.add(FileUtil.getDocumentPath()); } } catch (Exception ex) { ex.printStackTrace(); } finally { try { if (rs != null) rs.close(); if (stmt != null) stmt.close(); if (conn != null) conn.close(); } catch (Exception ex) { ex.printStackTrace(); } }*/ }
public void upgradeBaseSchema(Connection conn, int currentVersion) { if (!isLoaded()) { throw new TajoInternalError("Database schema files are not loaded."); } final List<SchemaPatch> candidatePatches = new ArrayList<>(); Statement stmt; for (SchemaPatch patch : this.catalogStore.getPatches()) { if (currentVersion >= patch.getPriorVersion()) { candidatePatches.add(patch); } } Collections.sort(candidatePatches); try { stmt = conn.createStatement(); } catch (SQLException e) { throw new TajoInternalError(e); } for (SchemaPatch patch : candidatePatches) { for (DatabaseObject object : patch.getObjects()) { try { stmt.executeUpdate(object.getSql()); LOG.info(object.getName() + " " + object.getType() + " was created or altered."); } catch (SQLException e) { throw new TajoInternalError(e); } } } CatalogUtil.closeQuietly(stmt); }
private void doShip(final GoodPayload payload, long timeInMillis, final ShipResponse response) throws NoSuchArticleException { final List<Long> goodsToShip = new ArrayList<>(); /* fetch good to ship ids */ for (Map.Entry<Long, Integer> entry : payload.getGoods().entrySet()) { Collection<Long> goodIds = namedJdbcTemplate .getJdbcOperations() .query( QUERY_FETCH_GOOD_IDS_TO_SHIP, new Object[] { /* article id */ entry.getKey(), /* goods count */ entry.getValue() }, new ShipStatCollector(response)); goodsToShip.addAll(goodIds); } if (goodsToShip.isEmpty()) { throw new NoSuchArticleException(); } logger.info("remove good ids: " + goodsToShip); MapSqlParameterSource mapSqlParameterSource = new MapSqlParameterSource(); mapSqlParameterSource.addValue("shipTime", new Timestamp(timeInMillis), Types.TIMESTAMP); mapSqlParameterSource.addValue("goods", goodsToShip); namedJdbcTemplate.update(QUERY_SHIP_GOODS_BY_IDS, mapSqlParameterSource); }
public void forgetSecGroupIncludeByIncludeIdx(long ClusterId, int IncludeGroupId) { if (indexByIncludeIdx == null) { return; } CFSecuritySecGroupIncludeByIncludeIdxKey key = ((ICFInternetSchema) schema.getBackingStore()) .getFactorySecGroupInclude() .newIncludeIdxKey(); key.setRequiredClusterId(ClusterId); key.setRequiredIncludeGroupId(IncludeGroupId); if (indexByIncludeIdx.containsKey(key)) { Map<CFSecuritySecGroupIncludePKey, ICFSecuritySecGroupIncludeObj> mapIncludeIdx = indexByIncludeIdx.get(key); if (mapIncludeIdx != null) { List<ICFSecuritySecGroupIncludeObj> toForget = new LinkedList<ICFSecuritySecGroupIncludeObj>(); ICFSecuritySecGroupIncludeObj cur = null; Iterator<ICFSecuritySecGroupIncludeObj> iter = mapIncludeIdx.values().iterator(); while (iter.hasNext()) { cur = iter.next(); toForget.add(cur); } iter = toForget.iterator(); while (iter.hasNext()) { cur = iter.next(); cur.forget(true); } } indexByIncludeIdx.remove(key); } }
/** * Find all the year records in a Calendar, it need not be a standard period (used in MRP) * * @param C_Calendar_ID calendar * @param ctx context * @param trx trx * @return MYear[] */ public static MYear[] getAllYearsInCalendar(int C_Calendar_ID, Ctx ctx, Trx trx) { List<MYear> years = new ArrayList<MYear>(); String sql = "SELECT * FROM C_Year WHERE " + "IsActive='Y' AND C_Calendar_ID = ? "; PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement(sql, trx); pstmt.setInt(1, C_Calendar_ID); rs = pstmt.executeQuery(); while (rs.next()) years.add(new MYear(ctx, rs, trx)); } catch (Exception e) { s_log.log(Level.SEVERE, sql, e); } finally { DB.closeResultSet(rs); DB.closeStatement(pstmt); } MYear[] retValue = new MYear[years.size()]; years.toArray(retValue); return retValue; }
public static boolean isZero(List list, String col) { if (list == null) { return false; } boolean b = false; int i, num = 0; String v = null; Map m = null; double dv = 0; num = list.size(); for (i = 0; i < num; i++) { m = (Map) list.get(i); v = (String) m.get(col); // if(f.empty(v)){return true;} if (f.empty(v)) { continue; } // System.out.println(v); v = f.v(v); dv = f.getDouble(v, 0); // if(dv==0){return true;} if (dv > 0) { return false; } b = true; } return b; }
@Test public void testEnums() { sql2o .createQuery( "create table EnumTest(id int identity primary key, enum_val varchar(10), enum_val2 int) ") .executeUpdate(); sql2o .createQuery("insert into EnumTest(enum_val, enum_val2) values (:val, :val2)") .addParameter("val", TestEnum.HELLO) .addParameter("val2", TestEnum.HELLO.ordinal()) .addToBatch() .addParameter("val", TestEnum.WORLD) .addParameter("val2", TestEnum.WORLD.ordinal()) .addToBatch() .executeBatch(); List<EntityWithEnum> list = sql2o .createQuery("select id, enum_val val, enum_val2 val2 from EnumTest") .executeAndFetch(EntityWithEnum.class); assertThat(list.get(0).val, is(TestEnum.HELLO)); assertThat(list.get(0).val2, is(TestEnum.HELLO)); assertThat(list.get(1).val, is(TestEnum.WORLD)); assertThat(list.get(1).val2, is(TestEnum.WORLD)); TestEnum testEnum = sql2o.createQuery("select 'HELLO' from (values(0))").executeScalar(TestEnum.class); assertThat(testEnum, is(TestEnum.HELLO)); TestEnum testEnum2 = sql2o.createQuery("select NULL from (values(0))").executeScalar(TestEnum.class); assertThat(testEnum2, is(nullValue())); }
@Test public void testCaseInsensitive() { sql2o .createQuery( "create table testCI(id2 int primary key, value2 varchar(20), sometext varchar(20), valwithgetter varchar(20))") .executeUpdate(); Query query = sql2o.createQuery( "insert into testCI(id2, value2, sometext, valwithgetter) values(:id, :value, :someText, :valwithgetter)"); for (int i = 0; i < 20; i++) { query .addParameter("id", i) .addParameter("value", "some text " + i) .addParameter("someText", "whatever " + i) .addParameter("valwithgetter", "spaz" + i) .addToBatch(); } query.executeBatch(); List<CIEntity> ciEntities = sql2o .createQuery("select * from testCI") .setCaseSensitive(false) .executeAndFetch(CIEntity.class); assertTrue(ciEntities.size() == 20); // test defaultCaseSensitive; sql2o.setDefaultCaseSensitive(false); List<CIEntity> ciEntities2 = sql2o.createQuery("select * from testCI").executeAndFetch(CIEntity.class); assertTrue(ciEntities2.size() == 20); }
public void forgetISOCountryCurrencyByCurrencyIdx(short ISOCurrencyId) { if (indexByCurrencyIdx == null) { return; } CFSecurityISOCountryCurrencyByCurrencyIdxKey key = ((ICFInternetSchema) schema.getBackingStore()) .getFactoryISOCountryCurrency() .newCurrencyIdxKey(); key.setRequiredISOCurrencyId(ISOCurrencyId); if (indexByCurrencyIdx.containsKey(key)) { Map<CFSecurityISOCountryCurrencyPKey, ICFSecurityISOCountryCurrencyObj> mapCurrencyIdx = indexByCurrencyIdx.get(key); if (mapCurrencyIdx != null) { List<ICFSecurityISOCountryCurrencyObj> toForget = new LinkedList<ICFSecurityISOCountryCurrencyObj>(); ICFSecurityISOCountryCurrencyObj cur = null; Iterator<ICFSecurityISOCountryCurrencyObj> iter = mapCurrencyIdx.values().iterator(); while (iter.hasNext()) { cur = iter.next(); toForget.add(cur); } iter = toForget.iterator(); while (iter.hasNext()) { cur = iter.next(); cur.forget(true); } } indexByCurrencyIdx.remove(key); } }
@Test public void testUtilDate() { sql2o .createQuery("create table testutildate(id int primary key, d1 datetime, d2 timestamp)") .executeUpdate(); sql2o .createQuery("insert into testutildate(id, d1, d2) values(:id, :d1, :d2)") .addParameter("id", 1) .addParameter("d1", new Date()) .addParameter("d2", new Date()) .addToBatch() .addParameter("id", 2) .addParameter("d1", new Date()) .addParameter("d2", new Date()) .addToBatch() .addParameter("id", 3) .addParameter("d1", new Date()) .addParameter("d2", new Date()) .addToBatch() .executeBatch(); List<UtilDateEntity> list = sql2o.createQuery("select * from testutildate").executeAndFetch(UtilDateEntity.class); assertTrue(list.size() == 3); }
/** * 生成泛型对应的ResultMap * * @param namespace * @param clazz * @param conf * @return */ private List<ResultMap> getResultMap(String namespace, Class<?> clazz, Configuration conf) { String dynamicResultMapId = namespace + "." + GENERATE_RESULT_MAP_NAME; ResultMap dynamicResultMap = buildResultMap(dynamicResultMapId, clazz, conf); List<ResultMap> resultMaps = Lists.newArrayList(); resultMaps.add(dynamicResultMap); return Collections.unmodifiableList(resultMaps); }
public void forgetSecDeviceByUserIdx(UUID SecUserId) { if (indexByUserIdx == null) { return; } CFSecuritySecDeviceByUserIdxKey key = ((ICFSecuritySchema) schema.getBackingStore()).getFactorySecDevice().newUserIdxKey(); key.setRequiredSecUserId(SecUserId); if (indexByUserIdx.containsKey(key)) { Map<CFSecuritySecDevicePKey, ICFSecuritySecDeviceObj> mapUserIdx = indexByUserIdx.get(key); if (mapUserIdx != null) { List<ICFSecuritySecDeviceObj> toForget = new LinkedList<ICFSecuritySecDeviceObj>(); ICFSecuritySecDeviceObj cur = null; Iterator<ICFSecuritySecDeviceObj> iter = mapUserIdx.values().iterator(); while (iter.hasNext()) { cur = iter.next(); toForget.add(cur); } iter = toForget.iterator(); while (iter.hasNext()) { cur = iter.next(); cur.forget(true); } } indexByUserIdx.remove(key); } }
/** * 构建ResultMap对象 * * @param id * @param clazz * @param configuration * @return */ private ResultMap buildResultMap(String id, Class<?> clazz, Configuration configuration) { // 判断是否已经存在缓存里 if (configuration.hasResultMap(id)) { return configuration.getResultMap(id); } List<ResultMapping> resultMappings = Lists.newArrayList(); Map<String, Field> columns = EntityUtil.getFields(clazz); for (Map.Entry<String, Field> column : columns.entrySet()) { Field field = column.getValue(); String fieldName = field.getName(); Class<?> columnTypeClass = resolveResultJavaType(clazz, fieldName, null); List<ResultFlag> flags = Lists.newArrayList(); if (field.isAnnotationPresent(Id.class)) { flags.add(ResultFlag.ID); } String columnName = column.getKey(); resultMappings.add( buildResultMapping(configuration, fieldName, columnName, columnTypeClass, flags)); } // 构建ResultMap ResultMap.Builder resultMapBuilder = new ResultMap.Builder(configuration, id, clazz, resultMappings); ResultMap rm = resultMapBuilder.build(); // 放到缓存中 configuration.addResultMap(rm); return rm; }
public List getBooksByCost(String cost) { List al = new ArrayList(); try { con = JdbcUtil.getMysqlConnection(); ps = con.prepareStatement("select *from jlcbooks where cost=?"); ps.setString(1, cost); rs = ps.executeQuery(); while (rs.next()) { Book bo = new Book(); bo.setBid(rs.getString(1)); bo.setBname(rs.getString(2)); bo.setAuthor(rs.getString(3)); bo.setPub(rs.getString(4)); bo.setCost(rs.getString(5)); bo.setEdi(rs.getString(6)); bo.setIsbn(rs.getString(7)); al.add(bo); } } catch (Exception e) { e.printStackTrace(); } finally { JdbcUtil.cleanup(ps, con); } return al; }
/** Creates a Pooled connection and adds it to the connection pool. */ private void installConnection() throws EmanagerDatabaseException { logger.debug("enter"); PooledConnection connection; try { connection = poolDataSource.getPooledConnection(); connection.addConnectionEventListener(this); connection.getConnection().setAutoCommit(false); synchronized (connectionPool) { connectionPool.add(connection); logger.debug("Database connection added."); } } catch (SQLException ex) { logger.fatal("exception caught while obtaining database " + "connection: ex = " + ex); SQLException ex1 = ex.getNextException(); while (ex1 != null) { logger.fatal("chained sql exception ex1 = " + ex1); SQLException nextEx = ex1.getNextException(); ex1 = nextEx; } String logString; EmanagerDatabaseException ede; logString = EmanagerDatabaseStatusCode.DatabaseConnectionFailure.getStatusCodeDescription() + ex.getMessage(); logger.fatal(logString); ede = new EmanagerDatabaseException( EmanagerDatabaseStatusCode.DatabaseConnectionFailure, logString); throw ede; } }
public void forgetTaxByTenantIdx(long TenantId) { if (indexByTenantIdx == null) { return; } CFAccTaxByTenantIdxKey key = ((ICFAccSchema) schema.getBackingStore()).getFactoryTax().newTenantIdxKey(); key.setRequiredTenantId(TenantId); if (indexByTenantIdx.containsKey(key)) { Map<CFAccTaxPKey, ICFAccTaxObj> mapTenantIdx = indexByTenantIdx.get(key); if (mapTenantIdx != null) { List<ICFAccTaxObj> toForget = new LinkedList<ICFAccTaxObj>(); ICFAccTaxObj cur = null; Iterator<ICFAccTaxObj> iter = mapTenantIdx.values().iterator(); while (iter.hasNext()) { cur = iter.next(); toForget.add(cur); } iter = toForget.iterator(); while (iter.hasNext()) { cur = iter.next(); cur.forget(true); } } indexByTenantIdx.remove(key); } }
@SuppressWarnings("unchecked") @Test public void testAppendCloudServiceGuidConstraint() throws Exception { CustomerDAO dao = new CustomerDAO(); // list List<String> list = new LinkedList<String>(); list.add("val1"); list.add("val2"); SearchConstraint sc = new SearchConstraint("TEST_PROP", SearchConstraintOperator.CONSTRAINT_IN_LIST, list); String got = dao.appendCloudServiceGuidConstraint(sc); String expected = CustomerDAO.SQL_CUSTOMER_QUERY_CLOUD_SERVICE_CONSTRAINT + "in (E'val1',E'val2'))"; assertEquals("Wrong constraint added.", expected, got); // equal sc = new SearchConstraint( ICustomerService.PROP_CLOUD_SERVICE_GUID, SearchConstraintOperator.CONSTRAINT_EQUALS, "val3"); got = dao.appendCloudServiceGuidConstraint(sc); expected = CustomerDAO.SQL_CUSTOMER_QUERY_CLOUD_SERVICE_CONSTRAINT + "= E'val3' and g_inner.disabled = false)"; assertEquals("Wrong constraint added.", expected, got); }
public ListIterator<ICFLibAnyObj> enumerateDetails(MssCFGenContext genContext) { final String S_ProcName = "CFBamMssCFIterateNumberTypeRef.enumerateDetails() "; if (genContext == null) { throw CFLib.getDefaultExceptionFactory() .newNullArgumentException(getClass(), S_ProcName, 1, "genContext"); } ICFLibAnyObj genDef = genContext.getGenDef(); if (genDef == null) { throw CFLib.getDefaultExceptionFactory() .newNullArgumentException(getClass(), S_ProcName, 1, "genContext.getGenDef()"); } List<ICFLibAnyObj> list = new LinkedList<ICFLibAnyObj>(); if (genDef instanceof ICFBamNumberTypeObj) { Iterator<ICFBamTableColObj> elements = ((ICFBamNumberTypeObj) genDef).getOptionalChildrenRef().iterator(); while (elements.hasNext()) { list.add(elements.next()); } } else { throw CFLib.getDefaultExceptionFactory() .newUnsupportedClassException( getClass(), S_ProcName, "genContext.getGenDef()", genDef, "ICFBamNumberTypeObj"); } return (list.listIterator()); }
public MetadataBlob[] select(String selectString) { PreparedStatement stmt = null; try { stmt = conn.prepareStatement( "select writingKey, mapkey, blobdata from metadatablobs " + selectString + ";"); ResultSet rs = stmt.executeQuery(); List<MetadataBlob> list = new ArrayList<MetadataBlob>(); while (rs.next()) { MetadataBlob f = new MetadataBlob( rs.getString("writingkey"), rs.getString("mapkey"), rs.getString("blobdata")); list.add(f); } return list.toArray(new MetadataBlob[0]); } catch (SQLException sqe) { System.err.println("Error selecting: " + selectString); sqe.printStackTrace(); return null; } finally { if (stmt != null) try { stmt.close(); } catch (SQLException sqe2) { sqe2.printStackTrace(); } } }