@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; }
@Test public void testJPAEntityFieldInfo() { JPAResponderGen rg = new JPAResponderGen(); EntityMetadata mdEntity = new EntityMetadata("Flight"); Vocabulary voc = new Vocabulary(); voc.setTerm(new TermValueType(TermValueType.INTEGER_NUMBER)); voc.setTerm(new TermIdField(true)); mdEntity.setPropertyVocabulary("ID", voc); voc = new Vocabulary(); voc.setTerm(new TermValueType(TermValueType.INTEGER_NUMBER)); mdEntity.setPropertyVocabulary("flightID", voc); mdEntity.setPropertyVocabulary("number", new Vocabulary()); mdEntity.setPropertyVocabulary("runway", new Vocabulary()); voc = new Vocabulary(); voc.setTerm(new TermValueType(TermValueType.TIMESTAMP)); mdEntity.setPropertyVocabulary("departureDT", voc); voc = new Vocabulary(); voc.setTerm(new TermValueType(TermValueType.DATE)); mdEntity.setPropertyVocabulary("departureDate", voc); voc = new Vocabulary(); voc.setTerm(new TermValueType(TermValueType.TIME)); mdEntity.setPropertyVocabulary("departureTime", voc); EntityInfo p = rg.createEntityInfoFromEntityMetadata("AirlineModel", mdEntity); assertEquals(6, p.getFieldInfos().size()); assertTrue(p.getFieldInfos().contains(new FieldInfo("flightID", "Long", null))); assertTrue(p.getFieldInfos().contains(new FieldInfo("number", "String", null))); assertTrue(p.getFieldInfos().contains(new FieldInfo("runway", "String", null))); assertTrue(p.getFieldInfos().contains(new FieldInfo("departureDT", "java.util.Date", null))); assertTrue(p.getFieldInfos().contains(new FieldInfo("departureDate", "java.util.Date", null))); assertTrue(p.getFieldInfos().contains(new FieldInfo("departureTime", "java.util.Date", null))); }
@Test public void testJPAEntityFieldInfoAnnotations() { JPAResponderGen rg = new JPAResponderGen(); EntityMetadata mdEntity = new EntityMetadata("Flight"); Vocabulary voc = new Vocabulary(); voc.setTerm(new TermValueType(TermValueType.INTEGER_NUMBER)); voc.setTerm(new TermIdField(true)); mdEntity.setPropertyVocabulary("ID", voc); voc = new Vocabulary(); voc.setTerm(new TermValueType(TermValueType.TIMESTAMP)); mdEntity.setPropertyVocabulary("departureDT", voc); voc = new Vocabulary(); voc.setTerm(new TermValueType(TermValueType.DATE)); mdEntity.setPropertyVocabulary("departureDate", voc); voc = new Vocabulary(); voc.setTerm(new TermValueType(TermValueType.TIME)); mdEntity.setPropertyVocabulary("departureTime", voc); EntityInfo p = rg.createEntityInfoFromEntityMetadata("AirlineModel", mdEntity); // Annotations FieldInfo dateOnlyFI = p.getFieldInfos().get(0); assertEquals(1, dateOnlyFI.getAnnotations().size()); assertEquals("@Temporal(TemporalType.DATE)", dateOnlyFI.getAnnotations().get(0)); FieldInfo timeFI = p.getFieldInfos().get(1); assertEquals(1, timeFI.getAnnotations().size()); assertEquals("@Temporal(TemporalType.TIME)", timeFI.getAnnotations().get(0)); FieldInfo dateFI = p.getFieldInfos().get(2); assertEquals(1, dateFI.getAnnotations().size()); assertEquals("@Temporal(TemporalType.TIMESTAMP)", dateFI.getAnnotations().get(0)); }
@Override public void insertEntity(MongoIdentifiableEntity entity, MongoStoreInvocationContext context) { Class<? extends MongoEntity> clazz = entity.getClass(); // Find annotations for ID, for all the properties and for the name of the collection. EntityInfo entityInfo = getEntityInfo(clazz); // Create instance of BasicDBObject and add all declared properties to it (properties with null // value probably should be skipped) BasicDBObject dbObject = mapperRegistry.convertApplicationObjectToDBObject(entity, BasicDBObject.class); DBCollection dbCollection = database.getCollection(entityInfo.getDbCollectionName()); String currentId = entity.getId(); // Generate random ID if not set already if (currentId == null) { currentId = KeycloakModelUtils.generateId(); entity.setId(currentId); } // Adding "_id" dbObject.put("_id", currentId); try { dbCollection.insert(dbObject); } catch (MongoException e) { throw convertException(e); } // Treat object as created in this transaction (It is already submited to transaction) context.addCreatedEntity(entity); }
/* * Add transition properties to entity info */ public static void addNavPropertiesToEntityInfo( EntityInfo entityInfo, InteractionModel interactionModel) { IMResourceStateMachine rsm = interactionModel.findResourceStateMachine(entityInfo.getClazz()); if (rsm != null) { for (IMTransition transition : rsm.getEntityStateTransitions()) { List<FieldInfo> properties = entityInfo.getAllFieldInfos(); List<String> annotations = new ArrayList<String>(); if (transition instanceof IMCollectionStateTransition) { // Transition to collection state // TODO fix reciprocal links // annotations.add("@OneToMany(cascade = CascadeType.ALL, mappedBy = \"" + // transition.getTargetStateName() + "\")"); // properties.add(new FieldInfo(transition.getTargetStateName(), "Collection<" + // transition.getTargetEntityName() + ">", annotations)); } else if (transition instanceof IMEntityStateTransition) { // Transition to entity state IMEntityStateTransition t = (IMEntityStateTransition) transition; annotations.add( "@JoinColumn(name = \"" + t.getLinkProperty() + "\", referencedColumnName = \"" + t.getTargetResourceStateMachine().getMappedEntityProperty() + "\", insertable = false, updatable = false)"); annotations.add("@ManyToOne(optional = false)"); properties.add( new FieldInfo( t.getTargetState().getName(), t.getTargetResourceStateMachine().getEntityName(), annotations)); } } } }
@Override public <S> boolean pushItemToList( final MongoIdentifiableEntity entity, final String listPropertyName, S itemToPush, boolean skipIfAlreadyPresent, MongoStoreInvocationContext context) { final Class<? extends MongoEntity> type = entity.getClass(); EntityInfo entityInfo = getEntityInfo(type); // Add item to list directly in this object Property<Object> listProperty = entityInfo.getPropertyByName(listPropertyName); if (listProperty == null) { throw new IllegalArgumentException( "Property " + listPropertyName + " doesn't exist on object " + entity); } List<S> list = (List<S>) listProperty.getValue(entity); if (list == null) { list = new ArrayList<S>(); listProperty.setValue(entity, list); } // Skip if item is already in list if (skipIfAlreadyPresent && list.contains(itemToPush)) { return false; } // Update java object list.add(itemToPush); // Add update of list to pending tasks final List<S> listt = list; context.addUpdateTask( entity, new MongoTask() { @Override public void execute() { // Now DB update of new list with usage of $set BasicDBList dbList = mapperRegistry.convertApplicationObjectToDBObject(listt, BasicDBList.class); BasicDBObject query = new BasicDBObject("_id", entity.getId()); BasicDBObject listObject = new BasicDBObject(listPropertyName, dbList); BasicDBObject setCommand = new BasicDBObject("$set", listObject); getDBCollectionForType(type).update(query, setCommand); } @Override public boolean isFullUpdate() { return false; } }); return true; }
private boolean generateJPAEntity(EntityInfo entityInfo, File srcOutputPath) { // Generate JPA class if (entityInfo.isJpaEntity()) { String path = srcOutputPath.getPath() + "/" + entityInfo.getPackageAsPath(); if (!writeClass( path, formClassFilename(path, entityInfo), generateJPAEntityClass(entityInfo))) { return false; } } return true; }
@Override public int del(Object id, Class clazz) throws Exception { EntityInfo entityInfo = ClassUtils.getEntityInfoByClazz(clazz); if (entityInfo == null) { throw new DaoException("无效的实体类class"); } SqlHelper sqlHelper = SqlHelper.getDeleteHelper(clazz); sqlHelper.append(" WHERE ").append(entityInfo.getPkClumnName()).append("=?"); sqlHelper.setParameters(id); return del(sqlHelper, clazz); }
/** * 检查表 * * @param clazz */ public void checkOrCreateTable(Class clazz) { EntityInfo info = EntityInfo.build(clazz); if (info.isChecked()) { return; } else { boolean isexit = checkTable(info.table); if (!isexit) { String sql = getCreatTableSQL(clazz); db.execSQL(sql); } info.setChecked(true); } }
@Override public <S> boolean pullItemFromList( final MongoIdentifiableEntity entity, final String listPropertyName, final S itemToPull, MongoStoreInvocationContext context) { final Class<? extends MongoEntity> type = entity.getClass(); EntityInfo entityInfo = getEntityInfo(type); // Remove item from list directly in this object Property<Object> listProperty = entityInfo.getPropertyByName(listPropertyName); if (listProperty == null) { throw new IllegalArgumentException( "Property " + listPropertyName + " doesn't exist on object " + entity); } List<S> list = (List<S>) listProperty.getValue(entity); // If list is null, we skip both object and DB update if (list == null || !list.contains(itemToPull)) { return false; } else { // Update java object list.remove(itemToPull); // Add update of list to pending tasks context.addUpdateTask( entity, new MongoTask() { @Override public void execute() { // Pull item from DB Object dbItemToPull = mapperRegistry.convertApplicationObjectToDBObject(itemToPull, Object.class); BasicDBObject query = new BasicDBObject("_id", entity.getId()); BasicDBObject pullObject = new BasicDBObject(listPropertyName, dbItemToPull); BasicDBObject pullCommand = new BasicDBObject("$pull", pullObject); getDBCollectionForType(type).update(query, pullCommand); } @Override public boolean isFullUpdate() { return false; } }); return true; } }
@Override public Map<String, Object> findMapById(Object id, Class clazz) throws Exception { EntityInfo entityInfo = ClassUtils.getEntityInfoByClazz(clazz); if (entityInfo == null) { throw new DaoException("无效的实体类class"); } SqlHelper sqlHelper = SqlHelper.getSelectHelper(clazz); sqlHelper.append(" AND ").append(entityInfo.getPkClumnName()).append("=?"); sqlHelper.setParameters(id); return searchMapForOne(sqlHelper); }
@Test public void testEntityInfo() { JPAResponderGen rg = new JPAResponderGen(); EntityMetadata mdEntity = new EntityMetadata("Flight"); Vocabulary voc = new Vocabulary(); voc.setTerm(new TermValueType(TermValueType.INTEGER_NUMBER)); voc.setTerm(new TermIdField(true)); mdEntity.setPropertyVocabulary("ID", voc); EntityInfo p = rg.createEntityInfoFromEntityMetadata("AirlineModel", mdEntity); assertEquals("Flight", p.getClazz()); assertEquals("AirlineModel", p.getPackage()); assertEquals("AirlineModel.Flight", p.getFQTypeName()); }
@Test public void testJPAEntityKeyInfo() { JPAResponderGen rg = new JPAResponderGen(); EntityMetadata mdEntity = new EntityMetadata("Flight"); Vocabulary voc = new Vocabulary(); voc.setTerm(new TermValueType(TermValueType.INTEGER_NUMBER)); voc.setTerm(new TermIdField(true)); mdEntity.setPropertyVocabulary("flightID", voc); EntityInfo p = rg.createEntityInfoFromEntityMetadata("AirlineModel", mdEntity); assertEquals("flightID", p.getKeyInfo().getName()); assertEquals("Long", p.getKeyInfo().getType()); assertEquals(0, p.getFieldInfos().size()); }
@Override public void batchDel(List<Object> ids, Class clazz) throws Exception { EntityInfo entityInfo = ClassUtils.getEntityInfoByClazz(clazz); if (entityInfo == null) { throw new DaoException("无效的实体类class"); } Object[] objects = new Object[ids.size()]; Arrays.fill(objects, "?"); SqlHelper sqlHelper = SqlHelper.getDeleteHelper(clazz); sqlHelper .append(" WHERE ") .append(entityInfo.getPkClumnName()) .append(" IN (") .append(StringUtils.join(objects, ",")) .append(")"); update(sqlHelper.getSql(), ids); }
@Override public BulkObject createBulkObject(RowValues values) { String type = values.get(StringTable.Type); if (type.endsWith("Error")) { return new BulkError(); } if (ADDITIONAL_OBJECT_MAP.containsKey(type)) { return ADDITIONAL_OBJECT_MAP.get(type).get(); } if (!INDIVIDUAL_ENTITY_MAP.containsKey(type)) { return new UnknownBulkEntity(); } EntityInfo info = INDIVIDUAL_ENTITY_MAP.get(type); if ("Deleted".equals(values.get(StringTable.Status)) && !(info.getDeleteAllColumnName() == null || info.getDeleteAllColumnName().isEmpty()) && (values.get(info.getDeleteAllColumnName()) == null || values.get(info.getDeleteAllColumnName()).isEmpty())) { return info.getIdentifierCreator().create(); } return info.getCreator().create(); }
private void loadEntities(InputStream is) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line; Set<String> uniqueDisplayNames = new HashSet<String>(); // TODO(dkogan): We're currently dropping entities with the same // name on the floor (e.g. we keep only one rib). Need to come // up with a better scheme so we can cycle through 'dups'. while ((line = reader.readLine()) != null) { String layer = line; int layerId = Layers.fromName(layer); while ((line = reader.readLine()) != null) { if ("".equals(line)) break; // Using substring() instead of split() is about 30% faster. // Explicitly use |new String()| because just substring() makes // the substring a view of the original string, which wastes // memory. int startIndex = 0, endIndex = line.indexOf(FIELD_SEPARATOR); String entityId = new String(line.substring(startIndex, endIndex)); startIndex = endIndex + 1; endIndex = line.indexOf(FIELD_SEPARATOR, startIndex); String entityName = new String(line.substring(startIndex, endIndex)); // Map of entity id to coordinate info (bbox, ctr). EntityInfo entityInfo = parseEntityInfo(line, endIndex + 1); entityInfo.layer = layerId; entityInfo.displayName = entityName; mEntities.put(entityId, entityInfo); // Map of display name to entity id. if (!uniqueDisplayNames.contains(entityName)) { mSearchList.add(entityName); uniqueDisplayNames.add(entityName); mSearchToEntity.put(entityName, new ArrayList<String>()); } mSearchToEntity.get(entityName).add(entityId); } } }
private static CharSequence createElementSQLJoin( final Map<Class, String> joinTabalis, final EntityInfo info, final FilterJoinNode node) { if (node.joinClass == null) return null; StringBuilder sb = new StringBuilder(); String[] joinColumns = node.joinColumns; sb.append(" INNER JOIN ") .append(node.joinEntity.getTable()) .append(" ") .append(joinTabalis.get(node.joinClass)) .append(" ON ") .append(info.getSQLColumn("a", joinColumns[0])) .append(" = ") .append(node.joinEntity.getSQLColumn(joinTabalis.get(node.joinClass), joinColumns[0])); for (int i = 1; i < joinColumns.length; i++) { sb.append(" AND ") .append(info.getSQLColumn("a", joinColumns[i])) .append(" = ") .append(node.joinEntity.getSQLColumn(joinTabalis.get(node.joinClass), joinColumns[i])); } return sb; }
/** * 对象封装 * * @param cursor * @param clazz * @return */ private <T> T cursorToBean(Cursor cursor, Class<T> clazz) { EntityInfo entity = EntityInfo.build(clazz); Set<String> keys = entity.getColumns().keySet(); T obj = null; try { obj = clazz.newInstance(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } for (Iterator<String> iterator = keys.iterator(); iterator.hasNext(); ) { String key = iterator.next(); String column = entity.getColumns().get(key); Field field = BeanUtil.getDeclaredField(clazz, key); if (field.getType().equals(Integer.class) || field.getType().equals(int.class)) { BeanUtil.setProperty(obj, key, cursor.getInt(cursor.getColumnIndex(column))); } else if (field.getType().equals(Long.class) || field.getType().equals(long.class)) { BeanUtil.setProperty(obj, key, cursor.getLong(cursor.getColumnIndex(column))); } else if (field.getType().equals(Double.class) || field.getType().equals(double.class)) { BeanUtil.setProperty(obj, key, cursor.getDouble(cursor.getColumnIndex(column))); } else if (field.getType().equals(Float.class) || field.getType().equals(float.class)) { BeanUtil.setProperty(obj, key, cursor.getFloat(cursor.getColumnIndex(column))); } else if (field.getType().equals(String.class)) { BeanUtil.setProperty(obj, key, cursor.getString(cursor.getColumnIndex(column))); } else if (field.getType().equals(Date.class)) { try { BeanUtil.setProperty(obj, key, new Date(cursor.getLong(cursor.getColumnIndex(column)))); } catch (Exception e) { } } else if (field.getType().equals(Boolean.class) || field.getType().equals(boolean.class)) { BeanUtil.setProperty( obj, key, cursor.getInt(cursor.getColumnIndex(column)) == 0 ? false : true); } } return obj; }
private static String getCreatTableSQL(Class<?> clazz) { EntityInfo info = EntityInfo.build(clazz); StringBuffer sql = new StringBuffer(); sql.append("CREATE TABLE IF NOT EXISTS "); sql.append(info.getTable()); sql.append(" ( "); Map<String, String> propertys = info.getColumns(); Set<String> keys = propertys.keySet(); for (Iterator<String> iterator = keys.iterator(); iterator.hasNext(); ) { String key = iterator.next(); sql.append(propertys.get(key)); Class<?> dataType = BeanUtil.getDeclaredField(clazz, key).getType(); if (dataType == int.class || dataType == Integer.class || dataType == long.class || dataType == Long.class) { sql.append(" INTEGER"); } else if (dataType == float.class || dataType == Float.class || dataType == double.class || dataType == Double.class) { sql.append(" REAL"); } else if (dataType == boolean.class || dataType == Boolean.class) { sql.append(" NUMERIC"); } if (key.equals(info.pk)) { sql.append(" PRIMARY KEY"); if (info.pkAuto) { sql.append(" AUTOINCREMENT"); } } sql.append(","); } sql.deleteCharAt(sql.length() - 1); sql.append(" )"); return sql.toString(); }
public SqlHelper getUpdateSql(Map<String, Object> object, EntityInfo entityInfo) { Object id = object.get(entityInfo.getPkName()); if (id == null) { throw new DaoException("缺少主键id参数"); } object.remove(entityInfo.getPkName()); SqlHelper sqlHelper = new SqlHelper("UPDATE "); sqlHelper.append(entityInfo.getTableName()).append(" SET "); // List<String> columns = new ArrayList<String>(); List<Object> values = new ArrayList<Object>(); Map<String, String> ptcMap = ClassUtils.propToColumnMap.get(entityInfo.getClazzName()); StringBuilder columnSql = new StringBuilder(); for (Map.Entry<String, Object> entry : object.entrySet()) { if (entry.getValue() != null) { values.add(entry.getValue()); if (!"".equals(columnSql.toString())) { columnSql.append(","); } columnSql.append(ptcMap.get(entry.getKey())); columnSql.append("="); columnSql.append("?"); } } if (values.size() < 1) { throw new DaoException("没有要更新的参数"); } sqlHelper.append(columnSql.toString()); sqlHelper.append(" WHERE "); sqlHelper.append(entityInfo.getPkClumnName()); sqlHelper.append("=?"); return sqlHelper; }
protected void initManagedCollections(Class<?>[] managedEntityTypes) { for (Class<?> clazz : managedEntityTypes) { EntityInfo entityInfo = getEntityInfo(clazz); String dbCollectionName = entityInfo.getDbCollectionName(); if (dbCollectionName != null && !database.collectionExists(dbCollectionName)) { DBCollection dbCollection = database.getCollection(dbCollectionName); logger.debug( "Created collection " + dbCollection.getName() + " in " + this.database.getName()); MongoIndex index = clazz.getAnnotation(MongoIndex.class); if (index != null) { createIndex(dbCollection, index); } MongoIndexes indexes = clazz.getAnnotation(MongoIndexes.class); if (indexes != null) { for (MongoIndex i : indexes.value()) { createIndex(dbCollection, i); } } } } }
private EntityInfo parseEntityInfo(String line, int pos) { EntityInfo result = new EntityInfo(); result.bblx = parseFloat(line, pos); pos = line.indexOf(FIELD_SEPARATOR, pos + 1) + 1; result.bbly = parseFloat(line, pos); pos = line.indexOf(FIELD_SEPARATOR, pos + 1) + 1; result.bblz = parseFloat(line, pos); pos = line.indexOf(FIELD_SEPARATOR, pos + 1) + 1; result.bbhx = parseFloat(line, pos); pos = line.indexOf(FIELD_SEPARATOR, pos + 1) + 1; result.bbhy = parseFloat(line, pos); pos = line.indexOf(FIELD_SEPARATOR, pos + 1) + 1; result.bbhz = parseFloat(line, pos); return result; }
/** * Utility method to form class filename. * * @param srcTargetDir * @param entityInfo * @return */ public static String formClassFilename(String path, EntityInfo entityInfo) { return path + "/" + entityInfo.getClazz() + ".java"; }
protected DBCollection getDBCollectionForType(Class<?> type) { EntityInfo entityInfo = getEntityInfo(type); String dbCollectionName = entityInfo.getDbCollectionName(); return dbCollectionName == null ? null : database.getCollection(dbCollectionName); }
/** * * 加载 * * @param clazz * @param id * @return */ public <T> T load(Class<T> clazz, Object id) { EntityInfo info = EntityInfo.build(clazz); return queryFrist(clazz, info.getPk() + "=?", id); }