Search in sources :

Example 31 with ReflectUtil

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

the class TestDb method testOrmUtil.

public void testOrmUtil() throws Exception {
    String[] fields = new ReflectUtil(Master.class).getFieldsName();
    System.out.println(Arrays.asList(fields));
    Master m = DAOFactory.getDAO(Master.class).fetch("pets").selectAll().queryOne();
    System.out.println(m);
}
Also used : Master(test.po.Master) ReflectUtil(org.eweb4j.util.ReflectUtil)

Example 32 with ReflectUtil

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

the class ManyToManyDAO method init.

public void init(Object t, List<Field> fields) throws DAOException {
    this.t = t;
    this.fields = fields;
    this.ru = new ReflectUtil(this.t);
    this.table = ORMConfigBeanUtil.getTable(this.t.getClass(), true);
    String idField = ORMConfigBeanUtil.getIdField(this.t.getClass());
    //		Method idSetter = ru.getSetter(idField);
    //		if (idSetter == null)
    //			throw new DAOException("can not get idSetter.", null);
    Method idGetter = ru.getGetter(idField);
    if (idGetter != null) {
        try {
            Object _idVal = idGetter.invoke(this.t);
            this.idVal = _idVal == null ? null : String.valueOf(_idVal);
        } catch (Exception e) {
            throw new DAOException(idGetter + " invoke exception ", e);
        }
    }
}
Also used : DAOException(org.eweb4j.orm.dao.DAOException) ReflectUtil(org.eweb4j.util.ReflectUtil) Method(java.lang.reflect.Method) DAOException(org.eweb4j.orm.dao.DAOException)

Example 33 with ReflectUtil

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

the class ManyToManyDAO method select.

/**
	 * 多对多级联查询 
	 * 1.当主对象没有包含任何一个关联对象时,默认查询所有与之关联的对象
	 * 2.当主对象中包含了关联对象时(含有其toRefVal值),则只查询这些关联的对象
	 * 
	 */
public void select() throws DAOException {
    if (this.fields == null || this.fields.size() == 0)
        return;
    // select tarClass from {tarTable} t, {relTable} r where r.to = t.toRefCol and r.from = {fromRefVal} order by r.xxx desc
    // select %s from {tarTable} where {toRefCol} in (select {to} from {relTable} where {from} = {fromRefVal} order by xxx desc)
    //		String format = "SELECT %s FROM %s WHERE %s IN (SELECT %s FROM %s WHERE %s = ? %s)";
    final String format = "select %s from %s, %s r where r.%s = %s.%s and r.%s = ? %s ";
    for (Field f : fields) {
        Method tarGetter = ru.getGetter(f.getName());
        if (tarGetter == null)
            continue;
        ManyToMany ann = tarGetter.getAnnotation(ManyToMany.class);
        if (ann == null) {
            ann = f.getAnnotation(ManyToMany.class);
            if (ann == null)
                continue;
        }
        JoinTable join = tarGetter.getAnnotation(JoinTable.class);
        if (join == null) {
            join = f.getAnnotation(JoinTable.class);
            if (join == null)
                continue;
        }
        JoinColumn[] froms = join.joinColumns();
        if (froms == null || froms.length == 0)
            continue;
        JoinColumn[] tos = join.inverseJoinColumns();
        if (tos == null || tos.length == 0)
            continue;
        // 多对多关系目标Class
        Class<?> tarClass = ann.targetEntity();
        if (void.class.isAssignableFrom(tarClass)) {
            tarClass = ClassUtil.getGenericType(f);
        }
        String tarTable = ORMConfigBeanUtil.getTable(tarClass, true);
        OrderBy orderAnn = tarGetter.getAnnotation(OrderBy.class);
        if (orderAnn == null)
            orderAnn = f.getAnnotation(OrderBy.class);
        String orderBy = "";
        if (orderAnn != null && orderAnn.value().trim().length() > 0)
            orderBy = " ORDER BY " + orderAnn.value().replace("t.", tarClass.getSimpleName().toLowerCase() + ".");
        // 目标类对应的数据库表Id字段
        String toRefCol = tos[0].referencedColumnName();
        if (toRefCol == null || toRefCol.trim().length() == 0)
            toRefCol = ORMConfigBeanUtil.getIdColumn(tarClass);
        String toRefField = ORMConfigBeanUtil.getField(tarClass, toRefCol);
        // 目标类在第三方关系表中的字段名
        String to = tos[0].name();
        // 第三方关系表
        String relTable = join.name();
        // 主类在第三方关系表中的字段名
        String from = froms[0].name();
        String fromRefCol = froms[0].referencedColumnName();
        if (fromRefCol == null || fromRefCol.trim().length() == 0)
            fromRefCol = ORMConfigBeanUtil.getIdColumn(t);
        String fromRefField = ORMConfigBeanUtil.getField(t.getClass(), fromRefCol);
        try {
            List<?> tarList = null;
            tarList = (List<?>) tarGetter.invoke(t);
            if (tarList != null && tarList.size() > 0) {
                for (int i = 0; i < tarList.size(); i++) {
                    Object tarObj = tarList.get(i);
                    ReflectUtil tarRu = new ReflectUtil(tarObj);
                    Method toRefFieldGetter = tarRu.getGetter(toRefField);
                    if (toRefFieldGetter == null)
                        throw new DAOException("can not find the 'to ref field -> " + toRefField + "' of " + tarClass + " 's getter method", null);
                    Object _obj = toRefFieldGetter.invoke(tarObj);
                    if (_obj == null)
                        continue;
                    String toRefVal = String.valueOf(_obj);
                    // 查询 select %s from {tarTable} where {tarIdColumn} = {tarIdVal}
                    tarObj = DAOFactory.getSelectDAO(dsName).selectOne(tarClass, new String[] { toRefField }, new String[] { toRefVal });
                }
            } else {
                // "select %s from %s, %s r where r.%s = %s.%s and r.%s = ? %s "
                // select tarClass from {tarTable} t, {relTable} r where r.to = t.toRefCol and r.from = ? order by r.xxx desc
                String sql = String.format(format, ORMConfigBeanUtil.getSelectAllColumn(tarClass), tarTable, relTable, to, tarClass.getSimpleName().toLowerCase(), toRefCol, from, orderBy);
                // 从数据库中取出与当前主对象fromRefCol关联的所有目标对象,
                Method fromRefFieldGetter = ru.getGetter(fromRefField);
                if (fromRefFieldGetter == null)
                    throw new DAOException("can not find the 'from ref field -> " + fromRefField + "' of " + t.getClass() + " 's getter method", null);
                Object _obj = fromRefFieldGetter.invoke(t);
                String fromRefVal = null;
                if (_obj != null)
                    fromRefVal = String.valueOf(_obj);
                tarList = DAOFactory.getSelectDAO(dsName).selectBySQL(tarClass, sql, fromRefVal);
            }
            // 并注入到当前主对象的属性中
            Method tarSetter = ru.getSetter(f.getName());
            tarSetter.invoke(t, tarList);
        } catch (Exception e) {
            e.printStackTrace();
            throw new DAOException("", e);
        }
    }
}
Also used : OrderBy(javax.persistence.OrderBy) ManyToMany(javax.persistence.ManyToMany) Method(java.lang.reflect.Method) DAOException(org.eweb4j.orm.dao.DAOException) DAOException(org.eweb4j.orm.dao.DAOException) Field(java.lang.reflect.Field) ReflectUtil(org.eweb4j.util.ReflectUtil) JoinColumn(javax.persistence.JoinColumn) JoinTable(javax.persistence.JoinTable)

Example 34 with ReflectUtil

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

the class OneToManyDAO method init.

/**
	 * 初始化
	 * 
	 * @param t
	 * @param fields
	 * @throws DAOException
	 */
public void init(Object t, List<Field> fields) throws DAOException {
    this.t = t;
    this.fields = fields;
    this.ru = new ReflectUtil(this.t);
    this.table = ORMConfigBeanUtil.getTable(this.t.getClass(), true);
    // 主类的ID属性名
    String idField = ORMConfigBeanUtil.getIdField(this.t.getClass());
    Method idGetter = ru.getGetter(idField);
    //		if (idGetter == null)
    //			throw new DAOException("can not find idGetter.", null);
    Object idVal = null;
    if (idGetter != null) {
        try {
            idVal = idGetter.invoke(this.t);
            this.idVal = idVal == null ? null : String.valueOf(idVal);
        } catch (Exception e) {
            throw new DAOException(idGetter + " invoke exception ", e);
        }
    }
}
Also used : DAOException(org.eweb4j.orm.dao.DAOException) ReflectUtil(org.eweb4j.util.ReflectUtil) Method(java.lang.reflect.Method) DAOException(org.eweb4j.orm.dao.DAOException)

Example 35 with ReflectUtil

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

the class OneToManyDAO method insert.

/**
	 * 一对多(主从)级联插入 。 
	 * 1. 如果主对象id值没有,将主对象插入数据库,否则不插入 
	 * 2. 遍历从对象,找到mappedBy 
	 * 3. 注入主对象,插入关系
	 * 4. 如果找不到mappedBy,则先找@JoinTable,然后判断次对象是否id值,如果没有就插入次对象,否则不插入,
	 * 8. 检查下是否有重复关系,接着插入关系表
	 * 5. 如果找不到@JoinTable,则根据主对象 class 在从对象属性中找。然后注入主对象,插入关系。
	 */
public void insert() throws DAOException {
    if (this.fields == null || this.fields.size() == 0)
        return;
    final Class<?> ownClass = ru.getObject().getClass();
    Transaction.execute(new Trans() {

        @Override
        public void run(Object... args) throws Exception {
            //检查主对象是否有ID值,若没有、插入数据库否则不用
            if (idVal == null || "0".equals(idVal) || "".equals(idVal)) {
                Number _idVal = DAOFactory.getInsertDAO(dsName).insert(t);
                if (_idVal == null || _idVal.intValue() <= 0)
                    throw new Exception("can not inster the main obj into db");
            } else if (DAOFactory.getSelectDAO(dsName).selectOneById(t) == null) {
                throw new Exception("the main object'id val is invalid!");
            }
            String fromRefVal = null;
            for (Field f : fields) {
                Method fGetter = ru.getGetter(f.getName());
                if (fGetter == null)
                    continue;
                OneToMany oneToMany = null;
                if (f.isAnnotationPresent(OneToMany.class)) {
                    oneToMany = f.getAnnotation(OneToMany.class);
                } else if (fGetter.isAnnotationPresent(OneToMany.class)) {
                    oneToMany = fGetter.getAnnotation(OneToMany.class);
                } else {
                    continue;
                }
                Class<?> tarClass = oneToMany.targetEntity();
                if (void.class.isAssignableFrom(tarClass)) {
                    tarClass = ClassUtil.getGenericType(f);
                }
                List<?> fList = null;
                try {
                    fList = (List<?>) fGetter.invoke(t);
                } catch (Exception e) {
                    throw new DAOException(fGetter + " invoke exception ", e);
                }
                if (fList == null)
                    continue;
                for (int i = 0; i < fList.size(); i++) {
                    Object tarObj = fList.get(i);
                    if (tarObj == null)
                        continue;
                    ReflectUtil tarRu = new ReflectUtil(tarObj);
                    String mappedBy = oneToMany.mappedBy();
                    if (mappedBy != null && mappedBy.trim().length() > 0) {
                        Method ownFieldSetter = tarRu.getSetter(mappedBy);
                        if (ownFieldSetter == null)
                            continue;
                        // finished
                        ownFieldSetter.invoke(tarObj, ru.getObject());
                        Models.inst(tarObj).create();
                    } else {
                        JoinTable joinTable = null;
                        if (f.isAnnotationPresent(JoinTable.class)) {
                            joinTable = f.getAnnotation(JoinTable.class);
                        } else if (fGetter.isAnnotationPresent(JoinTable.class)) {
                            joinTable = fGetter.getAnnotation(JoinTable.class);
                        } else {
                            // find ownclass in tarObj fields
                            for (Field tarObjField : tarRu.getFields()) {
                                if (tarObjField.getType().getName().equals(ownClass.getName())) {
                                    Method ownFieldSetter = tarRu.getSetter(tarObjField.getName());
                                    if (ownFieldSetter == null)
                                        continue;
                                    // finished
                                    ownFieldSetter.invoke(tarObj, ru.getObject());
                                    Models.inst(tarObj).create();
                                    break;
                                }
                            }
                        }
                        if (joinTable != null) {
                            JoinColumn[] froms = joinTable.joinColumns();
                            if (froms == null || froms.length == 0)
                                continue;
                            String from = froms[0].name();
                            JoinColumn[] tos = joinTable.inverseJoinColumns();
                            if (tos == null || tos.length == 0)
                                continue;
                            String to = tos[0].name();
                            String relTable = joinTable.name();
                            String fromRefCol = froms[0].referencedColumnName();
                            if (fromRefCol == null || fromRefCol.trim().length() == 0)
                                fromRefCol = ORMConfigBeanUtil.getIdColumn(t);
                            String fromRefField = ORMConfigBeanUtil.getField(t.getClass(), fromRefCol);
                            Method fromRefFieldGetter = ru.getGetter(fromRefField);
                            if (fromRefFieldGetter == null)
                                throw new Exception("can not find the 'from ref field -> " + fromRefField + "' of " + t.getClass() + " 's getter method");
                            Object _obj = fromRefFieldGetter.invoke(t);
                            if (_obj == null)
                                continue;
                            fromRefVal = String.valueOf(_obj);
                            String toRefCol = tos[0].referencedColumnName();
                            if (toRefCol == null || toRefCol.trim().length() == 0)
                                toRefCol = ORMConfigBeanUtil.getIdColumn(tarClass);
                            String toRefField = ORMConfigBeanUtil.getField(tarClass, toRefCol);
                            Method toRefFieldGetter = tarRu.getGetter(toRefField);
                            if (toRefFieldGetter == null)
                                throw new Exception("can not find the 'to ref field -> " + toRefField + "' of " + tarClass + " 's getter method");
                            Object _obj2 = toRefFieldGetter.invoke(t);
                            if (_obj2 == null)
                                continue;
                            String toRefVal = String.valueOf(_obj2);
                            // 插入到关系表中
                            // 先检查下是否有重复记录
                            // "select {from},{to} from {relTable} where {from} = {fromRefVal} and {to} = {toRefVal} "
                            String _format = "select %s, %s from %s where %s = ? and %s = ? ";
                            String _sql = String.format(_format, from, to, relTable, from, to);
                            if (DAOFactory.getSelectDAO(dsName).selectBySQL(Map.class, _sql, fromRefVal, toRefVal) != null)
                                continue;
                            // insert into relTable (from, to) values(?, ?) ;
                            String format = "insert into %s(%s, %s) values(?, ?) ;";
                            String sql = String.format(format, relTable, from, to);
                            DAOFactory.getUpdateDAO(dsName).updateBySQLWithArgs(sql, fromRefVal, toRefVal);
                        }
                    }
                }
            }
        }
    });
}
Also used : Method(java.lang.reflect.Method) OneToMany(javax.persistence.OneToMany) DAOException(org.eweb4j.orm.dao.DAOException) DAOException(org.eweb4j.orm.dao.DAOException) Field(java.lang.reflect.Field) ReflectUtil(org.eweb4j.util.ReflectUtil) List(java.util.List) Trans(org.eweb4j.orm.jdbc.transaction.Trans) JoinTable(javax.persistence.JoinTable)

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