查询并缓存结果
@param entityClass 实体类class (用户组装实际的缓存key)
@param key 缓存的key（和entityClass一起组成真实的缓存key。<br>如entityClass=UserEntity.class,key=findlist，实际的key为：UserEntity.findlist）
@param expireSeconds 过期时间，单位：秒
@param dataCaller 缓存不存在数据加载源
@return
175647
public static <T> T queryTryCache(Class<? extends BaseEntity> entityClass,String key,long expireSeconds,Callable<T> dataCaller){
		
		if(CacheHandler.cacheProvider == null){
			try {
				return dataCaller.call();
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		}
		
		String entityClassName = entityClass.getSimpleName();
		key = entityClassName + CacheHandler.SPLIT_PONIT + key;
		T result = CacheHandler.cacheProvider.get(key);
		if(result == null){
			try {				
				result = dataCaller.call();
				if(result != null){
					CacheHandler.cacheProvider.set(key, result, expireSeconds);
					String cacheGroupKey = entityClassName + CacheHandler.GROUPKEY_SUFFIX;
					CacheHandler.cacheProvider.putGroup(cacheGroupKey, key, expireSeconds);
				}
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		}
		return result;
	}
1246415
public <E> void delete(Class<E> entityClass, DatastoreKey parentKey, long id) {
    try {
      EntityMetadata entityMetadata = EntityIntrospector.introspect(entityClass);
      Key nativeKey = Key.newBuilder(parentKey.nativeKey(), entityMetadata.getKind(), id).build();
      nativeWriter.delete(nativeKey);
    } catch (DatastoreException exp) {
      throw DatastoreUtils.wrap(exp);
    }
  }
465646
public <E> List<E> find(Class<E> entityClass, Object... primaryKeys)
    {
        List<E> entities = new ArrayList<E>();
        if (primaryKeys == null)
        {
            return entities;
        }
        Set<Object> pKeys = new HashSet<Object>(Arrays.asList(primaryKeys));
        for (Object primaryKey : pKeys)
        {
            E e = find(entityClass, primaryKey);
            if (e != null)
            {
                entities.add(e);
            }
        }
        return entities;
    }
554280
public static String wherePKColumns(Class<?> entityClass, String entityName, boolean useVersion) {
        StringBuilder sql = new StringBuilder();
        boolean hasLogicDelete = hasLogicDeleteColumn(entityClass);

        sql.append("<where>");
        //获取全部列
        Set<EntityColumn> columnSet = EntityHelper.getPKColumns(entityClass);
        //当某个列有主键策略时，不需要考虑他的属性是否为空，因为如果为空，一定会根据主键策略给他生成一个值
        for (EntityColumn column : columnSet) {
            sql.append(" AND ").append(column.getColumnEqualsHolder(entityName));
        }
        if (useVersion) {
            sql.append(whereVersion(entityClass));
        }

        if (hasLogicDelete) {
            sql.append(whereLogicDelete(entityClass, false));
        }

        sql.append("</where>");
        return sql.toString();
    }
671261
private void processEntityClass(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        //引入JPA注解
        topLevelClass.addImportedType("javax.persistence.*");
        //lombok扩展开始
        //如果需要Data，引入包，代码增加注解
        if (this.needsData) {
            topLevelClass.addImportedType("lombok.Data");
            topLevelClass.addAnnotation("@Data");
        }
        //如果需要Getter，引入包，代码增加注解
        if (this.needsGetter) {
            topLevelClass.addImportedType("lombok.Getter");
            topLevelClass.addAnnotation("@Getter");
        }
        //如果需要Setter，引入包，代码增加注解
        if (this.needsSetter) {
            topLevelClass.addImportedType("lombok.Setter");
            topLevelClass.addAnnotation("@Setter");
        }
        //如果需要ToString，引入包，代码增加注解
        if (this.needsToString) {
            topLevelClass.addImportedType("lombok.ToString");
            topLevelClass.addAnnotation("@ToString");
        }
        //如果需要Getter，引入包，代码增加注解
        if (this.needsAccessors) {
            topLevelClass.addImportedType("lombok.experimental.Accessors");
            topLevelClass.addAnnotation("@Accessors(chain = true)");
        }
        //如果需要Getter，引入包，代码增加注解
        if (this.needsEqualsAndHashCode) {
            topLevelClass.addImportedType("lombok.EqualsAndHashCode");
            topLevelClass.addAnnotation("@EqualsAndHashCode");
        }
        //lombok扩展结束
        // region swagger扩展
        if (this.needsSwagger) {
            //导包
            topLevelClass.addImportedType("io.swagger.annotations.ApiModel");
            topLevelClass.addImportedType("io.swagger.annotations.ApiModelProperty");
            //增加注解(去除注释中的转换符)
            String remarks = introspectedTable.getRemarks();
            if (remarks == null) {
                remarks = "";
            }
            topLevelClass.addAnnotation("@ApiModel(\"" + remarks.replaceAll("\r", "").replaceAll("\n", "") + "\")");
        }
        // endregion swagger扩展
        String tableName = introspectedTable.getFullyQualifiedTableNameAtRuntime();
        //如果包含空格，或者需要分隔符，需要完善
        if (StringUtility.stringContainsSpace(tableName)) {
            tableName = context.getBeginningDelimiter()
                    + tableName
                    + context.getEndingDelimiter();
        }
        //是否忽略大小写，对于区分大小写的数据库，会有用
        if (caseSensitive && !topLevelClass.getType().getShortName().equals(tableName)) {
            topLevelClass.addAnnotation("@Table(name = \"" + getDelimiterName(tableName) + "\")");
        } else if (!topLevelClass.getType().getShortName().equalsIgnoreCase(tableName)) {
            topLevelClass.addAnnotation("@Table(name = \"" + getDelimiterName(tableName) + "\")");
        } else if (StringUtility.stringHasValue(schema)
                || StringUtility.stringHasValue(beginningDelimiter)
                || StringUtility.stringHasValue(endingDelimiter)) {
            topLevelClass.addAnnotation("@Table(name = \"" + getDelimiterName(tableName) + "\")");
        } else if (forceAnnotation) {
            topLevelClass.addAnnotation("@Table(name = \"" + getDelimiterName(tableName) + "\")");
        }
        if (generateColumnConsts) {
            for (IntrospectedColumn introspectedColumn : introspectedTable.getAllColumns()) {
                Field field = new Field();
                field.setVisibility(JavaVisibility.PUBLIC);
                field.setStatic(true);
                field.setFinal(true);
                field.setName(introspectedColumn.getActualColumnName().toUpperCase()); //$NON-NLS-1$
                field.setType(new FullyQualifiedJavaType(String.class.getName())); //$NON-NLS-1$
                field.setInitializationString("\"" + introspectedColumn.getJavaProperty() + "\"");
                context.getCommentGenerator().addClassComment(topLevelClass, introspectedTable);
                topLevelClass.addField(field);
                //增加字段名常量,用于pageHelper
                Field columnField = new Field();
                columnField.setVisibility(JavaVisibility.PUBLIC);
                columnField.setStatic(true);
                columnField.setFinal(true);
                columnField.setName("DB_" + introspectedColumn.getActualColumnName().toUpperCase()); //$NON-NLS-1$
                columnField.setType(new FullyQualifiedJavaType(String.class.getName())); //$NON-NLS-1$
                columnField.setInitializationString("\"" + introspectedColumn.getActualColumnName() + "\"");
                topLevelClass.addField(columnField);
            }
        }
        if (generateDefaultInstanceMethod) {
            Method defaultMethod = new Method();
            defaultMethod.setStatic(true);
            defaultMethod.setName("defaultInstance");
            defaultMethod.setVisibility(JavaVisibility.PUBLIC);
            defaultMethod.setReturnType(topLevelClass.getType());
            defaultMethod.addBodyLine(String.format("%s instance = new %s();", topLevelClass.getType().getShortName(), topLevelClass.getType().getShortName()));
            for (IntrospectedColumn introspectedColumn : introspectedTable.getAllColumns()) {
                String shortName = introspectedColumn.getFullyQualifiedJavaType().getShortName();
                List<String> supportType = Arrays.asList("Byte", "Short", "Character", "Integer", "Long", "Float", "Double", "String", "BigDecimal", "BigInteger");
                if (!supportType.contains(shortName)) {
                    continue;
                }
                if (introspectedColumn.getDefaultValue() != null) {
                    String defaultValue = introspectedColumn.getDefaultValue();
                    //去除前后'',如 '123456' -> 123456
                    if (defaultValue.startsWith("'") && defaultValue.endsWith("'")) {
                        if (defaultValue.length() == 2) {
                            defaultValue = "";
                        } else {
                            defaultValue = defaultValue.substring(1, defaultValue.length() - 1);
                        }
                    }
                    //暂不支持时间类型默认值识别,不同数据库表达式不同
                    if ("Boolean".equals(shortName)) {
                        if ("0".equals(defaultValue)) {
                            defaultValue = "false";
                        } else if ("1".equals(defaultValue)) {
                            defaultValue = "true";
                        }
                    }
                    //通过 new 方法转换
                    defaultMethod.addBodyLine(String.format("instance.%s = new %s(\"%s\");", introspectedColumn.getJavaProperty(), shortName, defaultValue));
                }

            }
            defaultMethod.addBodyLine("return instance;");
            topLevelClass.addMethod(defaultMethod);
        }
    }
966608
public final List findByRowKeys(Class entityClass, List<String> relationNames, boolean isWrapReq,
        EntityMetadata metadata, Object... rowIds) {
        List entities = null;

        MetamodelImpl metaModel =
            (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(metadata.getPersistenceUnit());

        EntityType entityType = metaModel.entity(metadata.getEntityClazz());

        List<AbstractManagedType> subManagedType = ((AbstractManagedType) entityType).getSubManagedType();

        try {
            if (!subManagedType.isEmpty()) {
                for (AbstractManagedType subEntity : subManagedType) {
                    EntityMetadata subEntityMetadata =
                        KunderaMetadataManager.getEntityMetadata(kunderaMetadata, subEntity.getJavaType());
                    entities = getDataHandler().fromThriftRow(entityClass, subEntityMetadata,
                        subEntityMetadata.getRelationNames(), isWrapReq, getConsistencyLevel(), rowIds);

                    if (entities != null && !entities.isEmpty()) {
                        break;
                    }
                }
            } else {
                entities = getDataHandler().fromThriftRow(entityClass, metadata, relationNames, isWrapReq,
                    getConsistencyLevel(), rowIds);
            }
        } catch (Exception e) {
            log.error("Error while retrieving records for entity {}, row keys {}", entityClass, rowIds);
            throw new KunderaException(e);
        }
        return entities;
    }
1274108
public T withManagedEntityClasses(Class<?>... entityClasses) {
        configMap.put(MANAGED_ENTITIES, Arrays.asList(entityClasses));
        return getThis();
    }
662969
public Boolean save(@NotNull V entity) {
        Timer saveAsyncTimer = METRICS.getTimer(MetricsType.DATA_PROVIDER_SAVE.name());

        Insert insert = QueryBuilder.insertInto(getEntityMetadata().getTableName());
        List<ColumnMetadata> columns = getEntityMetadata().getFieldMetaData();
        columns.forEach(column -> insert.value(column.getName(), QueryBuilder.bindMarker()));

        try {
            String keyspace = getEntityMetadata().getKeyspace();

            PreparedStatement prepare = getCassandraClient().prepare(keyspace, insert.getQueryString());
            prepare.setConsistencyLevel(getWriteConsistencyLevel());

            BoundStatement boundStatement = createBoundStatement(prepare, entity, columns);

            ResultSet input = getCassandraClient().execute(keyspace, boundStatement);

            return input.wasApplied();
        } catch (SyntaxError e) {
            LOGGER.warn("Can't prepare query: " + insert.getQueryString(), e);

        } finally {
            saveAsyncTimer.stop();
        }

        return false;
    }
1252327
@Override
    public Object find(Class entityClass, Object key)
    {
        return find(entityClass, key, null);
    }
388674
private ClassRecord getClassRecord(EntityIdValue entityIdValue) {
		if (!this.classRecords.containsKey(entityIdValue)) {
			ClassRecord classRecord = new ClassRecord();
			this.classRecords.put(entityIdValue, classRecord);
			return classRecord;
		} else {
			return this.classRecords.get(entityIdValue);
		}
	}
79481
private static Class<?> getIdClass(Class<?> entityClass) {
        Type[] genTypes = entityClass.getGenericInterfaces();

        for (int i = 0; i < genTypes.length; i++) {
            Type genType = genTypes[i];
            String s1 = genType.getClass().getName();
            String s2 = BaseEntity.class.getName();
            if (s1.startsWith(s2)) {
                Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
                // ID真实的class
                Class<?> mapperClass = (Class<?>) params[0];
                return mapperClass;
            }
        }

        return null;
    }
199925
public String wherePKColumns(Class<?> entityClass, boolean useVersion) {
        StringBuilder sql = new StringBuilder();
        sql.append("<where>");
        //获取全部列
        Set<EntityColumn> columnSet = EntityHelper.getPKColumns(entityClass);
        //当某个列有主键策略时，不需要考虑他的属性是否为空，因为如果为空，一定会根据主键策略给他生成一个值
        for (EntityColumn column : columnSet) {
            sql.append(" AND " + column.getColumnEqualsHolder(NEWER));
        }
        if (useVersion) {
            sql.append(whereVersion(entityClass));
        }
        sql.append("</where>");
        return sql.toString();
    }
494984
public OneStepDistributedRowLock<K, C> expireLockAfter(long timeout, TimeUnit unit) {
        this.timeout      = timeout;
        this.timeoutUnits = unit;
        return this;
    }
138564
public static void removeCache(Class<? extends BaseEntity> entityClass,String key){
    	if(CacheHandler.cacheProvider == null)return;
    	String entityClassName = entityClass.getSimpleName();
		key = entityClassName + CacheHandler.SPLIT_PONIT + key;
		String cacheGroupKey = entityClassName + CacheHandler.GROUPKEY_SUFFIX;
		
		CacheHandler.cacheProvider.remove(key);
		CacheHandler.cacheProvider.removeFromGroup(cacheGroupKey, key);
		
	}
1187273
public static String whereAllIfColumns(Class<?> entityClass, String entityName, boolean useVersion) {
        StringBuilder sql = new StringBuilder();
        sql.append("<where>");
        //获取全部列
        Set<EntityColumn> columnList = EntityHelper.getColumns(entityClass);
        //当某个列有主键策略时，不需要考虑他的属性是否为空，因为如果为空，一定会根据主键策略给他生成一个值
        for (EntityColumn column : columnList) {
            if (!useVersion || !column.getEntityField().isAnnotationPresent(Version.class)) {
                sql.append(SqlHelper.getIfNotNull(entityName,column, " AND " + column.getColumnEqualsHolder(entityName), false));
            }
        }
        if (useVersion) {
            sql.append(SqlHelper.whereVersion(entityClass));
        }
        sql.append("</where>");
        return sql.toString();
    }
1245142
public static <T> DataKey<T> create(String name, Class<T> dataClass) {
        return create(name, dataClass, true, null);
    }
548045
@Override
    public <T> T find(Class<T> entityClass, Object primaryKey)
    {
        try
        {
            return ivEm.find(entityClass, primaryKey);
        } finally
        {
            if (!inJTATransaction())
            {
                ivEm.clear();
            }
        }
    }