Search in sources :

Example 36 with ReflectUtil

use of org.eweb4j.util.ReflectUtil in project eweb4j-framework by laiweiwei.

the class ToOneDAO method select.

//	/**
//	 * 一对一级联更新
//	 */
//	public void update(long newIdVal) {
//		if (newIdVal <= 0 || this.fields == null || this.fields.size() == 0)
//			return;
//		if (idVal == null || "0".equals(idVal) || "".equals(idVal)) {
//			return;
//		} else if (DAOFactory.getSelectDAO(dsName).selectOne(t, this.idField) == null) {
//			// 检查一下当前对象的ID是否存在于数据库
//			return;
//		}
//		// "update {table} set {idCol} = {newIdVal} where {idCol} = {idVal}
//		//; update {tarTable} set {fkCol} = {newIdVal} where {fkCol} = {idVal}"
//		String format = "update %s set %s = %s where %s = %s ;";
//		for (Field f : fields) {
//			Method tarGetter = ru.getGetter(f.getName());
//			if (tarGetter == null)
//				continue;
//
//			OneToOne ann = tarGetter.getAnnotation(OneToOne.class);
//			if (ann == null) 
//				ann = f.getAnnotation(OneToOne.class);
//			
//			if (ann == null)
//				continue;
//			String mappedBy = ann.mappedBy();
//			String fk = null;
//			try {
//				Class<?> tarClass = ann.targetEntity();
//				if (void.class.isAssignableFrom(tarClass))
//					tarClass = f.getType();
//				
//				ReflectUtil tarRu = new ReflectUtil(tarClass);
//				Field[] tarFields = tarRu.getFields();
//				for (Field tarF : tarFields){
//					if (!f.getType().getName().equals(tarF.getType().getName()))
//						continue;
//					
//				    Method tarFGetter = tarRu.getGetter(tarF.getName());
//				    if (tarFGetter == null)
//				    	continue;
//				    
//				    OneToOne oneToOne = tarFGetter.getAnnotation(OneToOne.class);
//				    if (oneToOne == null)
//				    	oneToOne = tarF.getAnnotation(OneToOne.class);
//				    	if (oneToOne == null)
//				    		continue;
//					
//					JoinColumn joinColumn = tarFGetter.getAnnotation(JoinColumn.class);
//					if (joinColumn == null) 
//						joinColumn = tarF.getAnnotation(JoinColumn.class);
//						
//					
//					if (joinColumn == null)
//						fk = tarF.getName() + "_id";
//					else
//						fk = joinColumn.name();
//
//					String tarTable = ORMConfigBeanUtil.getTable(tarClass);
//				
//					// "update {table} set {idCol} = {newIdVal} where {idCol} = {idVal}
//					//; update {tarTable} set {fkCol} = {newIdVal} where {fkCol} = {idVal}"
//					final String sql1 = String.format(format, table, idColumn, newIdVal, idColumn, idVal);
//					final String sql2 = String.format(format, tarTable, fk, newIdVal, fk, idVal);
//					
//					Transaction.execute(new Trans() {
//						
//						@Override
//						public void run(Object... args) throws Exception {
//							DAOFactory.getUpdateDAO(dsName).updateBySQL(sql1);
//							DAOFactory.getUpdateDAO(dsName).updateBySQL(sql2);						
//						}
//					});
//					
//					break;
//				}
//			} catch (Exception e) {
//				throw new DAOException("", e);
//			}
//		}
//	}
/**
	 * 多对一级联查询 1.获取当前idVal,然后作为条件查询出其外键值,接着通过其外键值查出主对象数据,注入到当前
	 */
public void select() {
    if (this.fields == null || this.fields.size() == 0)
        return;
    if (idVal == null || "0".equals(idVal) || "".equals(idVal)) {
        log.warn("skip cascade select cause this pojo has no @Id value");
        return;
    }
    for (Field f : fields) {
        Method tarGetter = ru.getGetter(f.getName());
        if (tarGetter == null)
            continue;
        String fk = null;
        OneToOne ann = tarGetter.getAnnotation(OneToOne.class);
        if (ann == null)
            ann = f.getAnnotation(OneToOne.class);
        if (ann == null) {
            ManyToOne moAn = tarGetter.getAnnotation(ManyToOne.class);
            if (moAn == null)
                moAn = f.getAnnotation(ManyToOne.class);
            if (moAn == null)
                continue;
        }
        String refCol = null;
        JoinColumn joinCol = f.getAnnotation(JoinColumn.class);
        if (joinCol == null)
            joinCol = tarGetter.getAnnotation(JoinColumn.class);
        if (joinCol == null)
            fk = f.getName() + "_id";
        else {
            fk = joinCol.name();
            refCol = joinCol.referencedColumnName();
        }
        Class<?> tarClass = f.getType();
        if (refCol == null || refCol.trim().length() == 0)
            refCol = ORMConfigBeanUtil.getIdColumn(tarClass);
        String refField = ORMConfigBeanUtil.getField(tarClass, refCol);
        try {
            Object _tarObj = tarGetter.invoke(t);
            Object tarObj = null;
            boolean flag = false;
            if (_tarObj != null) {
                Method refFieldGetter = new ReflectUtil(_tarObj).getGetter(refField);
                if (refFieldGetter != null && refFieldGetter.invoke(_tarObj) != null)
                    tarObj = DAOFactory.getSelectDAO(dsName).selectOne(_tarObj, refField);
                else
                    flag = true;
            } else
                flag = true;
            if (flag) {
                // select * from {tarTable} where {referencedColumn} = (select {fk} from {table} where {idColumn} = {idVal})
                String format = "select %s from %s where %s = (select %s from %s where %s = %s )";
                String tarTable = ORMConfigBeanUtil.getTable(tarClass, true);
                String sql = String.format(format, ORMConfigBeanUtil.getSelectAllColumn(tarClass), tarTable, refCol, fk, table, idColumn, idVal);
                List<?> tarList = DAOFactory.getSelectDAO(dsName).selectBySQL(tarClass, sql);
                if (tarList == null || tarList.size() == 0)
                    continue;
                tarObj = tarList.get(0);
            }
            if (tarObj == null)
                continue;
            Method tarSetter = ru.getSetter(f.getName());
            tarSetter.invoke(t, tarObj);
        } catch (Exception e) {
            throw new DAOException("", e);
        }
    }
}
Also used : Method(java.lang.reflect.Method) ManyToOne(javax.persistence.ManyToOne) DAOException(org.eweb4j.orm.dao.DAOException) DAOException(org.eweb4j.orm.dao.DAOException) Field(java.lang.reflect.Field) ReflectUtil(org.eweb4j.util.ReflectUtil) OneToOne(javax.persistence.OneToOne) JoinColumn(javax.persistence.JoinColumn)

Example 37 with ReflectUtil

use of org.eweb4j.util.ReflectUtil in project eweb4j-framework by laiweiwei.

the class PojoAnnotationConfig method getProperties.

private static List<Property> getProperties(Class<?> clazz, final List<Property> pList, final boolean requireSuper, Log log) throws Throwable {
    List<Property> result = new ArrayList<Property>();
    ReflectUtil ru;
    try {
        ru = new ReflectUtil(clazz);
        ru.setRequiredSuper(requireSuper);
    } catch (Throwable e) {
        log.warn(e.toString(), e);
        throw e;
    }
    for (Field f : ru.getFields()) {
        if (Collection.class.isAssignableFrom(f.getType()))
            continue;
        String name = f.getName();
        Method getter = ru.getGetter(name);
        if (getter == null)
            continue;
        Ignore igAnn = f.getAnnotation(Ignore.class);
        if (igAnn == null)
            igAnn = getter.getAnnotation(Ignore.class);
        if (igAnn != null)
            continue;
        Transient trans = f.getAnnotation(Transient.class);
        if (trans == null)
            trans = getter.getAnnotation(Transient.class);
        if (trans != null)
            continue;
        OneToMany manyAnn = getter.getAnnotation(OneToMany.class);
        if (manyAnn != null)
            continue;
        else {
            manyAnn = f.getAnnotation(OneToMany.class);
            if (manyAnn != null)
                continue;
        }
        ManyToMany manyManyAnn = getter.getAnnotation(ManyToMany.class);
        if (manyManyAnn != null)
            continue;
        else {
            manyManyAnn = f.getAnnotation(ManyToMany.class);
            if (manyManyAnn != null)
                continue;
        }
        Property p = new Property();
        if (Long.class.isAssignableFrom(f.getType()) || long.class.isAssignableFrom(f.getType()))
            p.setSize("20");
        else if (Integer.class.isAssignableFrom(f.getType()) || int.class.isAssignableFrom(f.getType()))
            p.setSize("8");
        else if (String.class.isAssignableFrom(f.getType()))
            p.setSize("255");
        else if (Boolean.class.isAssignableFrom(f.getType()) || boolean.class.isAssignableFrom(f.getType()))
            p.setSize("");
        else if (Float.class.isAssignableFrom(f.getType()) || float.class.isAssignableFrom(f.getType()))
            p.setSize("8");
        Id idAnn = getter.getAnnotation(Id.class);
        if (idAnn == null)
            idAnn = f.getAnnotation(Id.class);
        if (idAnn != null) {
            if (pList != null && hasIdProperty(pList))
                continue;
            p.setAutoIncrement("1");
            p.setPk("1");
            p.setSize("20");
        }
        Column colAnn = getter.getAnnotation(Column.class);
        if (colAnn == null) {
            colAnn = f.getAnnotation(Column.class);
        }
        String column = colAnn == null ? "" : colAnn.name();
        column = "".equals(column.trim()) ? name : column;
        p.setName(name);
        p.setColumn(column);
        p.setType(f.getType().getName());
        p.setNotNull("false");
        if (colAnn != null) {
            // int size = colAnn.length();
            p.setNotNull(String.valueOf(!colAnn.nullable()));
            p.setUnique(String.valueOf(colAnn.unique()));
        }
        if (ClassUtil.isPojo(f.getType())) {
            OneToOne oneAnn = getter.getAnnotation(OneToOne.class);
            if (oneAnn == null)
                oneAnn = f.getAnnotation(OneToOne.class);
            ManyToOne manyToOneAnn = null;
            if (oneAnn == null) {
                manyToOneAnn = getter.getAnnotation(ManyToOne.class);
                if (manyToOneAnn == null)
                    manyToOneAnn = f.getAnnotation(ManyToOne.class);
            }
            if (oneAnn != null || manyToOneAnn != null) {
                if (oneAnn != null)
                    p.setType(PropType.ONE_ONE);
                else
                    p.setType(PropType.MANY_ONE);
                JoinColumn joinColumn = getter.getAnnotation(JoinColumn.class);
                if (joinColumn == null)
                    joinColumn = f.getAnnotation(JoinColumn.class);
                if (joinColumn != null && joinColumn.name().trim().length() > 0)
                    p.setColumn(joinColumn.name());
                else
                    p.setColumn(f.getName() + "_id");
                p.setRelProperty(null);
                String refCol = null;
                if (joinColumn != null && joinColumn.referencedColumnName().trim().length() > 0) {
                    refCol = joinColumn.referencedColumnName();
                    if (refCol != null && refCol.trim().length() > 0) {
                        String relField = ORMConfigBeanUtil.getField(f.getType(), refCol);
                        if (relField != null && relField.trim().length() > 0)
                            p.setRelProperty(relField);
                    }
                }
                p.setRelClass(f.getType());
                p.setSize("20");
            }
        }
        result.add(p);
    }
    return result;
}
Also used : Ignore(org.eweb4j.orm.annotation.Ignore) ArrayList(java.util.ArrayList) ManyToMany(javax.persistence.ManyToMany) Method(java.lang.reflect.Method) OneToMany(javax.persistence.OneToMany) ManyToOne(javax.persistence.ManyToOne) ReflectUtil(org.eweb4j.util.ReflectUtil) Field(java.lang.reflect.Field) OneToOne(javax.persistence.OneToOne) JoinColumn(javax.persistence.JoinColumn) JoinColumn(javax.persistence.JoinColumn) Column(javax.persistence.Column) Transient(javax.persistence.Transient) Id(javax.persistence.Id) Property(org.eweb4j.orm.config.bean.Property)

Example 38 with ReflectUtil

use of org.eweb4j.util.ReflectUtil in project eweb4j-framework by laiweiwei.

the class DAOImpl method handleJoin.

/**
	 * 
	 * @date 2013-1-9 上午01:16:37
	 * @param type 0 innerJoin 1 leftOuterJoin 2 rightOuterJoin 3 fullOuterJoin
	 * @param _fieldName
	 * @param _alias
	 */
private void handleJoin(int type, String _fieldName, String _alias) {
    String[] fDots = _fieldName.split("\\.");
    String[] aDots = _alias.split("\\.");
    Class<?> currentClazz = this.clazz;
    for (int i = 0; i < fDots.length; i++) {
        String fieldName = fDots[i];
        String alias = aDots[i];
        ReflectUtil ru = null;
        try {
            ru = new ReflectUtil(currentClazz);
            Field field = ru.getField(fieldName);
            if (field == null)
                throw new Exception("field->" + fieldName + " invalid");
            Class<?> cls = ClassUtil.getGenericType(field);
            if (cls == null)
                throw new Exception("can not get the field->" + fieldName + " class");
            if (!ORMConfigBeanCache.containsKey(cls.getName()))
                throw new Exception("field->" + fieldName + " of " + cls.getName() + " is not entity");
            String table = ORMConfigBeanUtil.getTable(cls, true);
            joins.add(table);
            _AliasField a = new _AliasField(alias, cls.getSimpleName().toLowerCase(), cls);
            aliasMap.put(alias, a);
            currentClazz = cls;
        } catch (Throwable e) {
            log.error(e.toString(), e);
        }
    }
}
Also used : ReflectUtil(org.eweb4j.util.ReflectUtil) Field(java.lang.reflect.Field) SQLException(java.sql.SQLException)

Example 39 with ReflectUtil

use of org.eweb4j.util.ReflectUtil in project eweb4j-framework by laiweiwei.

the class DeleteSqlCreator method makeSQL.

private Sql makeSQL(T t) throws SqlCreateException {
    Sql sql = new Sql();
    Class<?> clazz = t.getClass();
    String idColumn;
    String idField;
    String table;
    HashMap<String, Object> map = null;
    Object idValue = null;
    if (Map.class.isAssignableFrom(clazz)) {
        map = (HashMap<String, Object>) t;
        idColumn = (String) map.get("idColumn");
        if (idColumn == null)
            idColumn = "id";
        idField = idColumn;
        table = (String) map.get("table");
        idValue = map.get("idValue");
    } else {
        idField = ORMConfigBeanUtil.getIdField(clazz);
        idColumn = ORMConfigBeanUtil.getIdColumn(clazz);
        table = ORMConfigBeanUtil.getTable(clazz, false);
        ReflectUtil ru = new ReflectUtil(t);
        Method idGetter = ru.getGetter(idField);
        //			}
        if (idGetter != null) {
            try {
                idValue = idGetter.invoke(t);
            } catch (Exception e) {
                throw new SqlCreateException(idGetter + " invoke exception " + e.toString(), e);
            }
        }
    }
    StringBuilder condition = new StringBuilder();
    condition.append(idColumn).append(" = ? ");
    //		condition.append("'" + idValue + "'");
    sql.args.add(idValue);
    sql.sql = String.format("DELETE FROM %s WHERE %s ;", table, condition);
    return sql;
}
Also used : ReflectUtil(org.eweb4j.util.ReflectUtil) Method(java.lang.reflect.Method)

Example 40 with ReflectUtil

use of org.eweb4j.util.ReflectUtil in project eweb4j-framework by laiweiwei.

the class UpdateSqlCreator method makeSQL.

private Sql makeSQL(T t, String[] fields, Object[] values) throws SqlCreateException {
    Sql sql = new Sql();
    Class<?> clazz = t.getClass();
    String table = ORMConfigBeanUtil.getTable(clazz, false);
    ReflectUtil ru = new ReflectUtil(t);
    String[] columns = ORMConfigBeanUtil.getColumns(clazz, fields);
    String idColumn = ORMConfigBeanUtil.getIdColumn(clazz);
    String idField = ORMConfigBeanUtil.getIdField(clazz);
    Method idGetter = ru.getGetter(idField);
    if (idGetter == null)
        throw new SqlCreateException("can not find id getter.");
    Object idValue = null;
    try {
        idValue = idGetter.invoke(t);
    } catch (Exception e) {
        throw new SqlCreateException(idGetter + " invoke exception " + e.toString(), e);
    }
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < columns.length; ++i) {
        String column = columns[i];
        if (sb.length() > 0)
            sb.append(", ");
        //			sb.append(column).append(" = '").append(values[i]).append("'");
        sb.append(column).append(" = ?");
        sql.args.add(values[i]);
    }
    //		String condition = new StringBuilder().append(idColumn).append(" = ").append("'").append(idValue).append("'").toString();
    String condition = new StringBuilder().append(idColumn).append(" = ? ").toString();
    sql.args.add(idValue);
    sql.sql = String.format("UPDATE %s SET %s WHERE %s ;", table, sb.toString(), condition);
    return sql;
}
Also used : ReflectUtil(org.eweb4j.util.ReflectUtil) Method(java.lang.reflect.Method)

Aggregations

ReflectUtil (org.eweb4j.util.ReflectUtil)49 Method (java.lang.reflect.Method)37 Field (java.lang.reflect.Field)26 JoinColumn (javax.persistence.JoinColumn)14 ManyToOne (javax.persistence.ManyToOne)10 ArrayList (java.util.ArrayList)9 OneToOne (javax.persistence.OneToOne)9 DAOException (org.eweb4j.orm.dao.DAOException)9 JoinTable (javax.persistence.JoinTable)7 HashMap (java.util.HashMap)6 ManyToMany (javax.persistence.ManyToMany)6 OneToMany (javax.persistence.OneToMany)6 ORMConfigBean (org.eweb4j.orm.config.bean.ORMConfigBean)6 Property (org.eweb4j.orm.config.bean.Property)6 Entry (java.util.Map.Entry)5 File (java.io.File)4 List (java.util.List)4 Map (java.util.Map)4 ConfigBean (org.eweb4j.config.bean.ConfigBean)4 Hashtable (java.util.Hashtable)3