Search in sources :

Example 41 with JoinColumn

use of javax.persistence.JoinColumn 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 42 with JoinColumn

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

the class UpdateSqlCreator method makeSQL.

private Sql makeSQL(T t, String[] fields) throws SqlCreateException {
    Sql sql = new Sql();
    Class<?> clazz = t.getClass();
    //if fields is empty
    if (fields == null || fields.length == 0) {
        fields = ORMConfigBeanUtil.getFields(clazz);
    }
    String table = ORMConfigBeanUtil.getTable(clazz, false);
    StringBuilder values = new StringBuilder();
    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);
    }
    for (int i = 0; i < fields.length; i++) {
        String field = fields[i];
        String column = columns[i];
        Method getter = ru.getGetter(field);
        if (getter == null)
            continue;
        try {
            Object _value = getter.invoke(t);
            if (_value == null)
                continue;
            Object value = null;
            if (ClassUtil.isPojo(_value.getClass())) {
                Field f = ru.getField(field);
                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) {
                    JoinColumn joinColAnn = getter.getAnnotation(JoinColumn.class);
                    if (joinColAnn == null)
                        joinColAnn = f.getAnnotation(JoinColumn.class);
                    if (joinColAnn != null && joinColAnn.referencedColumnName().trim().length() > 0) {
                        String refCol = joinColAnn.referencedColumnName();
                        String refField = ORMConfigBeanUtil.getField(_value.getClass(), refCol);
                        ReflectUtil tarRu = new ReflectUtil(_value);
                        Method tarFKGetter = tarRu.getGetter(refField);
                        value = tarFKGetter.invoke(_value);
                    } else {
                        ReflectUtil tarRu = new ReflectUtil(_value);
                        String tarFKField = ORMConfigBeanUtil.getIdField(_value.getClass());
                        if (tarFKField != null) {
                            Method tarFKGetter = tarRu.getGetter(tarFKField);
                            value = tarFKGetter.invoke(_value);
                        }
                    }
                }
                if (value == null)
                    continue;
            } else {
                value = _value;
            }
            if (values.length() > 0)
                values.append(", ");
            //				values.append(column).append(" = '").append(value).append("'");
            values.append(column).append(" = ? ");
            sql.args.add(value);
        } catch (Exception e) {
            throw new SqlCreateException(idGetter + " invoke exception " + e.toString(), e);
        }
    }
    //		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, values, condition);
    return sql;
}
Also used : Method(java.lang.reflect.Method) ManyToOne(javax.persistence.ManyToOne) ReflectUtil(org.eweb4j.util.ReflectUtil) Field(java.lang.reflect.Field) OneToOne(javax.persistence.OneToOne) JoinColumn(javax.persistence.JoinColumn)

Example 43 with JoinColumn

use of javax.persistence.JoinColumn 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)

Example 44 with JoinColumn

use of javax.persistence.JoinColumn in project requery by requery.

the class AttributeMember method processBasicColumnAnnotations.

private void processBasicColumnAnnotations(ElementValidator validator) {
    if (annotationOf(Key.class).isPresent() || annotationOf(javax.persistence.Id.class).isPresent()) {
        isKey = true;
        if (isTransient) {
            validator.error("Key field cannot be transient");
        }
    }
    // generated keys can't be set through a setter
    if (annotationOf(Generated.class).isPresent() || annotationOf(GeneratedValue.class).isPresent()) {
        isGenerated = true;
        isReadOnly = true;
        // check generation strategy
        annotationOf(GeneratedValue.class).ifPresent(generatedValue -> {
            if (generatedValue.strategy() != GenerationType.IDENTITY && generatedValue.strategy() != GenerationType.AUTO) {
                validator.warning("GeneratedValue.strategy() " + generatedValue.strategy() + " not supported", generatedValue.getClass());
            }
        });
    }
    if (annotationOf(Lazy.class).isPresent()) {
        if (isKey) {
            cannotCombine(validator, Key.class, Lazy.class);
        }
        isLazy = true;
    }
    if (annotationOf(Nullable.class).isPresent() || isOptional || Mirrors.findAnnotationMirror(element(), "javax.annotation.Nullable").isPresent()) {
        isNullable = true;
    } else {
        // if not a primitive type the value assumed nullable
        if (element().getKind().isField()) {
            isNullable = !element().asType().getKind().isPrimitive();
        } else if (element().getKind() == ElementKind.METHOD) {
            ExecutableElement executableElement = (ExecutableElement) element();
            isNullable = !executableElement.getReturnType().getKind().isPrimitive();
        }
    }
    if (annotationOf(Version.class).isPresent() || annotationOf(javax.persistence.Version.class).isPresent()) {
        isVersion = true;
        if (isKey) {
            cannotCombine(validator, Key.class, Version.class);
        }
    }
    Column column = annotationOf(Column.class).orElse(null);
    ForeignKey foreignKey = null;
    boolean foreignKeySetFromColumn = false;
    if (column != null) {
        name = "".equals(column.name()) ? null : column.name();
        isUnique = column.unique();
        isNullable = column.nullable();
        defaultValue = column.value();
        collate = column.collate();
        definition = column.definition();
        if (column.length() > 0) {
            length = column.length();
        }
        if (column.foreignKey().length > 0) {
            foreignKey = column.foreignKey()[0];
            foreignKeySetFromColumn = true;
        }
    }
    if (!foreignKeySetFromColumn) {
        foreignKey = annotationOf(ForeignKey.class).orElse(null);
    }
    if (foreignKey != null) {
        this.isForeignKey = true;
        deleteAction = foreignKey.delete();
        updateAction = foreignKey.update();
        referencedColumn = foreignKey.referencedColumn();
    }
    annotationOf(Index.class).ifPresent(index -> {
        isIndexed = true;
        Collections.addAll(indexNames, index.value());
    });
    // JPA specific
    annotationOf(Basic.class).ifPresent(basic -> {
        isNullable = basic.optional();
        isLazy = basic.fetch() == FetchType.LAZY;
    });
    annotationOf(javax.persistence.Index.class).ifPresent(index -> {
        isIndexed = true;
        Collections.addAll(indexNames, index.name());
    });
    annotationOf(JoinColumn.class).ifPresent(joinColumn -> {
        javax.persistence.ForeignKey joinForeignKey = joinColumn.foreignKey();
        this.isForeignKey = true;
        ConstraintMode constraintMode = joinForeignKey.value();
        switch(constraintMode) {
            default:
            case PROVIDER_DEFAULT:
            case CONSTRAINT:
                deleteAction = ReferentialAction.CASCADE;
                updateAction = ReferentialAction.CASCADE;
                break;
            case NO_CONSTRAINT:
                deleteAction = ReferentialAction.NO_ACTION;
                updateAction = ReferentialAction.NO_ACTION;
                break;
        }
        this.referencedTable = joinColumn.table();
        this.referencedColumn = joinColumn.referencedColumnName();
    });
    annotationOf(javax.persistence.Column.class).ifPresent(persistenceColumn -> {
        name = "".equals(persistenceColumn.name()) ? null : persistenceColumn.name();
        isUnique = persistenceColumn.unique();
        isNullable = persistenceColumn.nullable();
        length = persistenceColumn.length();
        isReadOnly = !persistenceColumn.updatable();
        definition = persistenceColumn.columnDefinition();
    });
    annotationOf(Enumerated.class).ifPresent(enumerated -> {
        EnumType enumType = enumerated.value();
        if (enumType == EnumType.ORDINAL) {
            converterType = EnumOrdinalConverter.class.getCanonicalName();
        }
    });
}
Also used : Basic(javax.persistence.Basic) ExecutableElement(javax.lang.model.element.ExecutableElement) Index(io.requery.Index) ConstraintMode(javax.persistence.ConstraintMode) ForeignKey(io.requery.ForeignKey) GeneratedValue(javax.persistence.GeneratedValue) Lazy(io.requery.Lazy) EnumOrdinalConverter(io.requery.converter.EnumOrdinalConverter) Enumerated(javax.persistence.Enumerated) JoinColumn(javax.persistence.JoinColumn) JoinColumn(javax.persistence.JoinColumn) Column(io.requery.Column) EnumType(javax.persistence.EnumType) Nullable(io.requery.Nullable)

Aggregations

JoinColumn (javax.persistence.JoinColumn)44 JoinTable (javax.persistence.JoinTable)17 Field (java.lang.reflect.Field)15 Method (java.lang.reflect.Method)14 ManyToOne (javax.persistence.ManyToOne)14 ReflectUtil (org.eweb4j.util.ReflectUtil)14 MapKeyJoinColumn (javax.persistence.MapKeyJoinColumn)13 PrimaryKeyJoinColumn (javax.persistence.PrimaryKeyJoinColumn)13 Test (org.junit.Test)12 JoinColumns (javax.persistence.JoinColumns)11 OneToOne (javax.persistence.OneToOne)10 UniqueConstraint (javax.persistence.UniqueConstraint)9 Column (javax.persistence.Column)8 ManyToMany (javax.persistence.ManyToMany)8 OneToMany (javax.persistence.OneToMany)6 DAOException (org.eweb4j.orm.dao.DAOException)6 Id (javax.persistence.Id)5 MapKeyJoinColumns (javax.persistence.MapKeyJoinColumns)5 HashMap (java.util.HashMap)4 CollectionTable (javax.persistence.CollectionTable)4