Search in sources :

Example 6 with Trans

use of org.eweb4j.orm.jdbc.transaction.Trans in project eweb4j-framework by laiweiwei.

the class ManyToManyDAO method update.

/**
	 * 一对多级联更新
	 */
public void update(Long newFromRefVal) {
    if (this.fields == null || this.fields.size() == 0)
        return;
    // "update {table} set {fromRefCol} = {newFromRefVal} where {fromRefCol} = {fromRefVal}
    // ; update {relTable} set {from} = {newFromRefVal} where {from} = {fromRefVal}"
    String format = "update %s set %s = %s where %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;
        // 第三方关系表
        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 {
            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);
            if (_obj == null)
                continue;
            String fromRefVal = String.valueOf(_obj);
            // "update {table} set {fromRefCol} = {newFromRefVal} where {fromRefCol} = {fromRefVal}
            // ; update {relTable} set {from} = {newFromRefVal} where {from} = {fromRefVal}"
            final String sql1 = String.format(format, table, fromRefCol, newFromRefVal, fromRefCol, fromRefVal);
            final String sql2 = String.format(format, relTable, from, newFromRefVal, from, fromRefVal);
            Transaction.execute(new Trans() {

                @Override
                public void run(Object... args) throws Exception {
                    DAOFactory.getUpdateDAO(dsName).updateBySQL(sql1);
                    DAOFactory.getUpdateDAO(dsName).updateBySQL(sql2);
                }
            });
        } catch (Exception e) {
            throw new DAOException("", e);
        }
    }
}
Also used : DAOException(org.eweb4j.orm.dao.DAOException) Field(java.lang.reflect.Field) JoinColumn(javax.persistence.JoinColumn) ManyToMany(javax.persistence.ManyToMany) Method(java.lang.reflect.Method) Trans(org.eweb4j.orm.jdbc.transaction.Trans) DAOException(org.eweb4j.orm.dao.DAOException) JoinTable(javax.persistence.JoinTable)

Example 7 with Trans

use of org.eweb4j.orm.jdbc.transaction.Trans 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

Trans (org.eweb4j.orm.jdbc.transaction.Trans)7 Field (java.lang.reflect.Field)3 Method (java.lang.reflect.Method)3 JoinTable (javax.persistence.JoinTable)3 DAOException (org.eweb4j.orm.dao.DAOException)3 List (java.util.List)2 JoinColumn (javax.persistence.JoinColumn)2 OneToMany (javax.persistence.OneToMany)2 ReflectUtil (org.eweb4j.util.ReflectUtil)2 BufferedReader (java.io.BufferedReader)1 File (java.io.File)1 FileInputStream (java.io.FileInputStream)1 IOException (java.io.IOException)1 InputStreamReader (java.io.InputStreamReader)1 ManyToMany (javax.persistence.ManyToMany)1 ManyToOne (javax.persistence.ManyToOne)1 ConfigBean (org.eweb4j.config.bean.ConfigBean)1 ListenerBean (org.eweb4j.config.bean.ListenerBean)1 Listeners (org.eweb4j.config.bean.Listeners)1 ActionAnnotationConfig (org.eweb4j.mvc.config.ActionAnnotationConfig)1