Search in sources :

Example 31 with DAOException

use of org.eweb4j.orm.dao.DAOException 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 32 with DAOException

use of org.eweb4j.orm.dao.DAOException 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 33 with DAOException

use of org.eweb4j.orm.dao.DAOException 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)

Example 34 with DAOException

use of org.eweb4j.orm.dao.DAOException 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 35 with DAOException

use of org.eweb4j.orm.dao.DAOException in project eweb4j-framework by laiweiwei.

the class DeleteDAOImpl method batchDelete.

public <T> Number[] batchDelete(T... ts) throws DAOException {
    Number[] ids = null;
    Connection con = null;
    if (ts == null || ts.length == 0)
        return ids;
    ids = new Number[ts.length];
    try {
        con = ds.getConnection();
        Sql[] sqls = SqlFactory.getDeleteSql(ts).delete();
        List<Object[]> argList = new ArrayList<Object[]>(ts.length);
        for (Sql sql : sqls) {
            argList.add(sql.args.toArray());
        }
        Object[][] args = new Object[argList.size()][];
        for (int i = 0; i < argList.size(); i++) {
            args[i] = argList.get(i);
        }
        ids = JdbcUtil.batchUpdateWithArgs(con, sqls[0].sql, args);
    } catch (Exception e) {
        throw new DAOException("", e);
    }
    return ids;
}
Also used : DAOException(org.eweb4j.orm.dao.DAOException) Connection(java.sql.Connection) ArrayList(java.util.ArrayList) DAOException(org.eweb4j.orm.dao.DAOException) Sql(org.eweb4j.orm.sql.Sql)

Aggregations

DAOException (org.eweb4j.orm.dao.DAOException)56 Connection (java.sql.Connection)42 Sql (org.eweb4j.orm.sql.Sql)13 Method (java.lang.reflect.Method)9 ReflectUtil (org.eweb4j.util.ReflectUtil)9 Field (java.lang.reflect.Field)7 ArrayList (java.util.ArrayList)6 JoinColumn (javax.persistence.JoinColumn)6 JoinTable (javax.persistence.JoinTable)6 ManyToMany (javax.persistence.ManyToMany)3 ManyToOne (javax.persistence.ManyToOne)3 OneToMany (javax.persistence.OneToMany)3 Trans (org.eweb4j.orm.jdbc.transaction.Trans)3 Master (test.po.Master)3 List (java.util.List)2 OrderBy (javax.persistence.OrderBy)2 Pet (test.po.Pet)2 OneToOne (javax.persistence.OneToOne)1