Search in sources :

Example 26 with JoinTable

use of javax.persistence.JoinTable 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 27 with JoinTable

use of javax.persistence.JoinTable 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 28 with JoinTable

use of javax.persistence.JoinTable in project eweb4j-framework by laiweiwei.

the class ManyToManyDAO method delete.

/**
	 * 多对多级联删除 
	 * 1.如果主对象不存在与数据库,不处理 
	 * 2.否则,检查当前主对象中的关联对象,如果关联对象为空,则删除所有与主对象有关的关联关系。
	 * 3.如果当前主对象中含有关联对象,则删除这些关联对象与主对象的关系
	 * 4.不会删除主对象
	 * 
	 */
public void delete() throws DAOException {
    if (this.fields == null || this.fields.size() == 0)
        return;
    // "delete from {relTable} WHERE {from} = {fromRefVal} ;"
    String format = "delete from %s WHERE %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;
        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);
        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);
        String fromRefVal = null;
        try {
            Object _obj = fromRefFieldGetter.invoke(t);
            if (_obj == null)
                continue;
            fromRefVal = String.valueOf(_obj);
        } catch (Exception e) {
            throw new DAOException("can not get the from ref val of " + t.getClass(), e);
        }
        List<?> tarList = null;
        try {
            tarList = (List<?>) tarGetter.invoke(t);
        } catch (Exception e) {
            throw new DAOException(tarGetter + " invoke exception, can not get the " + f.getName() + " objs ", e);
        }
        if (tarList == null || tarList.size() == 0) {
            String sql = String.format(format, relTable, from);
            // 删除所有关联记录
            DAOFactory.getUpdateDAO(dsName).updateBySQLWithArgs(sql, fromRefVal);
        } else {
            // 删除指定关联的记录
            Class<?> tarClass = ann.targetEntity();
            if (void.class.isAssignableFrom(tarClass)) {
                tarClass = ClassUtil.getGenericType(f);
            }
            String to = tos[0].name();
            String toRefCol = tos[0].referencedColumnName();
            if (toRefCol == null || toRefCol.trim().length() == 0)
                toRefCol = ORMConfigBeanUtil.getIdColumn(tarClass);
            String toRefField = ORMConfigBeanUtil.getField(tarClass, toRefCol);
            // "delete from {relTable} where {from} = {fromRefVal} and to = {toRefVal}"
            String _format = "delete from %s where %s = ? and %s = ?";
            for (int i = 0; i < tarList.size(); i++) {
                Object tarObj = tarList.get(i);
                if (tarObj == null)
                    continue;
                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);
                String toRefVal = null;
                try {
                    Object _obj = toRefFieldGetter.invoke(tarObj);
                    if (_obj == null)
                        continue;
                    toRefVal = String.valueOf(_obj);
                } catch (Exception e) {
                    throw new DAOException("can not get the to ref val of " + tarClass, e);
                }
                if (DAOFactory.getSelectDAO(dsName).selectOne(tarClass, new String[] { toRefField }, new String[] { toRefVal }) == null)
                    continue;
                String _sql = String.format(_format, relTable, from, to);
                DAOFactory.getUpdateDAO(dsName).updateBySQLWithArgs(_sql, fromRefVal, toRefVal);
            }
        }
    }
}
Also used : 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)

Aggregations

JoinTable (javax.persistence.JoinTable)28 JoinColumn (javax.persistence.JoinColumn)18 Test (org.junit.Test)9 Field (java.lang.reflect.Field)8 Method (java.lang.reflect.Method)8 ManyToMany (javax.persistence.ManyToMany)8 UniqueConstraint (javax.persistence.UniqueConstraint)7 ReflectUtil (org.eweb4j.util.ReflectUtil)7 MapKeyJoinColumn (javax.persistence.MapKeyJoinColumn)6 OneToMany (javax.persistence.OneToMany)6 DAOException (org.eweb4j.orm.dao.DAOException)6 PrimaryKeyJoinColumn (javax.persistence.PrimaryKeyJoinColumn)4 HashMap (java.util.HashMap)3 AssociationOverride (javax.persistence.AssociationOverride)3 CollectionTable (javax.persistence.CollectionTable)3 ElementCollection (javax.persistence.ElementCollection)3 ManyToOne (javax.persistence.ManyToOne)3 AnnotationException (org.hibernate.AnnotationException)3 XClass (org.hibernate.annotations.common.reflection.XClass)3 File (java.io.File)2