where主键条件

@param entityClass
@return
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();
    }
1181615
private void appendWhereIdList(StringBuilder sql, Class<?> entityClass, boolean notEmpty){
        Set<EntityColumn> columnList = EntityHelper.getPKColumns(entityClass);
        if (columnList.size() == 1) {
            EntityColumn column = columnList.iterator().next();
            if(notEmpty){
                sql.append("<bind name=\"notEmptyListCheck\" value=\"@tk.mybatis.mapper.additional.idlist.IdListProvider@notEmpty(");
                sql.append("idList, 'idList 不能为空')\"/>");
            }
            sql.append("<where>");
            sql.append("<foreach collection=\"idList\" item=\"id\" separator=\",\" open=\"");
            sql.append(column.getColumn());
            sql.append(" in ");
            sql.append("(\" close=\")\">");
            sql.append("#{id}");
            sql.append("</foreach>");
            sql.append("</where>");
        } else {
            throw new MapperException("继承 ByIdList 方法的实体类[" + entityClass.getCanonicalName() + "]中必须只有一个带有 @Id 注解的字段");
        }
    }
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();
    }
827475
public Optional<String> staticTableNameFor(Class<?> entityClass) {

        final Optional<String> tableName = entityProperties
                .stream()
                .filter(x -> x.entityClass.equals(entityClass))
                .map(x -> x.getKeyspace().map(ks -> ks + "." + x.getTableOrViewName()).orElseGet(x::getTableOrViewName))
                .findFirst();

        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace(format("Determining table name for entity type %s : %s",
                    entityClass.getCanonicalName(), tableName));
        }

        return tableName;
    }
548045
@Override
    public <T> T find(Class<T> entityClass, Object primaryKey)
    {
        try
        {
            return ivEm.find(entityClass, primaryKey);
        } finally
        {
            if (!inJTATransaction())
            {
                ivEm.clear();
            }
        }
    }
991293
public <T, K> DAO<T, K> getDAO(
                    final Class<T> entityClass
                    )
    {
        if (entityClass == null) {
            throw new ObjectTypeException( "entity type NOT specified (null)" );
        }

        DAO<T, K>  dao = null;
        try {
            @SuppressWarnings( "unchecked" )
            DAO<T, K>  dao_tmp = (DAO<T, K>)_daoMap.get( entityClass );
                                 //throws ClassCastException
            dao = dao_tmp;
        } catch (Exception ex) {
            throw new RepositoryConfigurationException( ex );
        }

        if (dao == null) {
            throw new RepositoryConfigurationException( "unknown entity type: " + entityClass );
        }

        return dao;
    }
107872
public static String exampleSelectColumns(Class<?> entityClass) {
        StringBuilder sql = new StringBuilder();
        sql.append("<choose>");
        sql.append("<when test=\"@tk.mybatis.mapper.util.OGNL@hasSelectColumns(_parameter)\">");
        sql.append("<foreach collection=\"_parameter.selectColumns\" item=\"selectColumn\" separator=\",\">");
        sql.append("${selectColumn}");
        sql.append("</foreach>");
        sql.append("</when>");
        //不支持指定列的时候查询全部列
        sql.append("<otherwise>");
        sql.append(getAllColumns(entityClass));
        sql.append("</otherwise>");
        sql.append("</choose>");
        return sql.toString();
    }
567201
public static EntityMapper getEntityMapper(Class<?> entityClass) {

        synchronized (entityClass) {
            // 先从map中获取实体映射信息
            EntityMapper entityMapper = tableMapperCache.get(entityClass);

            // 如果存在直接返回
            if (entityMapper != null) {
                return entityMapper;
            }

            TableMapper tableMapper = getTableMapper(entityClass);

            //获取实体ID泛型
            Class<?> idClass = getIdClass(entityClass);

            // 获取实体字段列表
            List<Field> fields = getAllField(entityClass);
            // 全部列
            Set<ColumnMapper> columnMapperSet = new HashSet<ColumnMapper>();
            // 主键
            ColumnMapper idColumn = null;
            GenerationType idStrategy = null;

            for (Field field : fields) {

                // 排除字段
                if (field.isAnnotationPresent(Transient.class)) {
                    continue;
                }
                ColumnMapper columnMapper = new ColumnMapper();

                // 数据库字段名
                String columnName = null;
                if (field.isAnnotationPresent(Column.class)) {
                    Column column = field.getAnnotation(Column.class);
                    columnName = column.name();
                    columnMapper.setInsertable(column.insertable());
                    columnMapper.setUpdatable(column.updatable());
                }
                // 如果为空，使用属性名并替换为下划线风格
                if (columnName == null || columnName.equals("")) {
                    columnName = camelhumpToUnderline(field.getName());
                }

                columnMapper.setProperty(field.getName());
                columnMapper.setColumn(columnName);
                columnMapper.setJavaType(field.getType());

                // 是否主键
                if(field.isAnnotationPresent(Id.class)){                	
                	columnMapper.setId(true);
                	if(field.isAnnotationPresent(GeneratedValue.class)){ 
                		idStrategy = field.getAnnotation(GeneratedValue.class).strategy();
                	}
                	idColumn = columnMapper;
                }
                // 添加到所有字段映射信息
                columnMapperSet.add(columnMapper);

            }
            if (columnMapperSet.size() <= 0) {
                throw new RuntimeException("实体" + entityClass.getName() + "不存在映射字段");
            }
            if (idColumn == null) {
                throw new RuntimeException("实体" + entityClass.getName() + "不存在主键");
            }

            // 解析实体映射信息
            entityMapper = new EntityMapper();
            entityMapper.setTableMapper(tableMapper);
            entityMapper.setColumnsMapper(columnMapperSet);
            entityMapper.setIdClass(idClass);
            entityMapper.setIdColumn(idColumn);
            entityMapper.setIdStrategy(idStrategy);

            tableMapperCache.put(entityClass, entityMapper);

            return entityMapper;
        }
    }
799562
public <T> Page<T> findAll(Pageable pageable, Class<T> entityClass, String privilegeKey) {
        String selectSql = format(SELECT_ALL_SQL, entityClass.getSimpleName());
        String countSql = format(COUNT_ALL_SQL, entityClass.getSimpleName());

        String permittedCondition = createPermissionCondition(privilegeKey);
        if (StringUtils.isNotBlank(permittedCondition)) {
            selectSql += WHERE_SQL + permittedCondition;
            countSql += WHERE_SQL + permittedCondition;
        }

        log.debug("Executing SQL '{}'", selectSql);

        return execute(createCountQuery(countSql), pageable, createSelectQuery(selectSql, pageable, entityClass));
    }
733576
public static ResultMap getResultMap(Configuration configuration,Class<?> entityClass) {
        List<ResultMapping> resultMappings = new ArrayList<ResultMapping>();
        
        Set<ColumnMapper> entityClassColumns = EntityHelper.getEntityMapper(entityClass).getColumnsMapper();
        for (ColumnMapper entityColumn : entityClassColumns) {
            ResultMapping.Builder builder = new ResultMapping.Builder(configuration, entityColumn.getProperty(), entityColumn.getColumn(), entityColumn.getJavaType());
            if (entityColumn.getJdbcType() != null) {
                builder.jdbcType(entityColumn.getJdbcType());
            }

            List<ResultFlag> flags = new ArrayList<ResultFlag>();
            if (entityColumn.isId()) {
                flags.add(ResultFlag.ID);
            }
            builder.flags(flags);
            builder.lazy(false);
            resultMappings.add(builder.build());
        }
        ResultMap.Builder builder = new ResultMap.Builder(configuration, "BaseResultMap", entityClass, resultMappings, true);
        return builder.build();
    }
1182639
public String updateSetColumnsByDiffer(Class<?> entityClass) {
        StringBuilder sql = new StringBuilder();
        sql.append("<set>");
        //获取全部列
        Set<EntityColumn> columnSet = EntityHelper.getColumns(entityClass);
        //对乐观锁的支持
        EntityColumn versionColumn = null;
        //当某个列有主键策略时，不需要考虑他的属性是否为空，因为如果为空，一定会根据主键策略给他生成一个值
        for (EntityColumn column : columnSet) {
            if (column.getEntityField().isAnnotationPresent(Version.class)) {
                if (versionColumn != null) {
                    throw new VersionException(entityClass.getCanonicalName() + " 中包含多个带有 @Version 注解的字段，一个类中只能存在一个带有 @Version 注解的字段!");
                }
                versionColumn = column;
            }
            if (!column.isId() && column.isUpdatable()) {
                if (column == versionColumn) {
                    Version version = versionColumn.getEntityField().getAnnotation(Version.class);
                    String versionClass = version.nextVersion().getCanonicalName();
                    //version = ${@tk.mybatis.mapper.version@nextVersionClass("versionClass", version)}
                    sql.append(column.getColumn())
                        .append(" = ${@tk.mybatis.mapper.version.VersionUtil@nextVersion(")
                        .append("@").append(versionClass).append("@class, ")
                        .append(column.getProperty()).append(")},");
                } else {
                    //if old.xx != newer.xx
                    sql.append(getIfNotEqual(column, column.getColumnEqualsHolder(NEWER) + ","));
                }
            }
        }
        sql.append("</set>");
        return sql.toString();
    }
1320905
private QueryMethodCache generateQueryByPKMethod(Class<?> mapperClass,Class<?> entityClass){
		QueryMethodCache methodCache = null;
		Field[] fields = entityClass.getDeclaredFields();
		//主键key前缀
		for (Field field : fields) {
			if(field.isAnnotationPresent(Id.class)){
				methodCache = new QueryMethodCache();
				methodCache.isPk = true;
				methodCache.collectionResult = false;
				methodCache.keyPattern = entityClass.getSimpleName() + ".id:%s";
				methodCache.methodName = mapperClass.getName() + "." + methodDefine.selectName();
				methodCache.cacheGroupKey = entityClass.getSimpleName() + GROUPKEY_SUFFIX;
			}
		}
		return methodCache;
	}
195687
@Override
    public <E> List<E> findAll(Class<E> entityClass, String[] columnsToSelect, Object... keys)
    {
        List entities = new ArrayList<E>();
        for (Object key : keys)
        {
            entities.add(find(entityClass, key));
        }
        return entities;
    }
1252327
@Override
    public Object find(Class entityClass, Object key)
    {
        return find(entityClass, key, null);
    }
534322
@Override
  public <T> T findById(Object id, Class<T> entityClass) {
    return findById(id, Util.determineCollectionName(entityClass));
  }
1313675
@Override
    public Object find(Class entityClass, Object rowId)
    {
        EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClass);
        Object enhancedEntity = null;
        if (rowId == null)
        {
            return null;
        }
        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
                m.getPersistenceUnit());
        if (metaModel.isEmbeddable(m.getIdAttribute().getBindableJavaType()))
        {
            rowId = KunderaCoreUtils.prepareCompositeKey(m, rowId);
        }
        try
        {
            List results = findData(m, rowId, null, null, null, null);
            if (results != null && !results.isEmpty())
            {
                enhancedEntity = results.get(0);
            }
        }
        catch (Exception e)
        {
            log.error("Error during find by id, Caused by: .", e);
            throw new KunderaException("Error during find by id, Caused by: .", e);
        }
        return enhancedEntity;
    }
677135
private static List<Field> getAllField(Class<?> entityClass, List<Field> fieldList) {
        if (fieldList == null) {
            fieldList = new ArrayList<Field>();
        }
        if (entityClass.equals(Object.class)) {
            return fieldList;
        }
        Field[] fields = entityClass.getDeclaredFields();
        for (Field field : fields) {
            // 排除静态字段
            if (!Modifier.isStatic(field.getModifiers())) {
                fieldList.add(field);
            }
        }
        Class<?> superClass = entityClass.getSuperclass();
        if (superClass != null && !superClass.equals(Object.class)
                && (!Map.class.isAssignableFrom(superClass) && !Collection.class.isAssignableFrom(superClass))) {
            return getAllField(entityClass.getSuperclass(), fieldList);
        }
        return fieldList;
    }