use of javax.persistence.JoinColumn in project eweb4j-framework by laiweiwei.
the class OneToManyDAO method delete.
/**
*
* 一对多(主从)级联删除
* 1.前提条件必须主对象要存在于数据库中
* 2.检查当前主对象中的关联对象,如果关联对象为空,则删除所有与主对象有关的关联关系。
* 3.如果当前主对象中含有关联对象,则删除这些关联对象与主对象的关系
* 4.不会删除主对象
*/
public void delete() 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 {
for (Field f : fields) {
Method tarGetter = ru.getGetter(f.getName());
if (tarGetter == null)
continue;
OneToMany ann = tarGetter.getAnnotation(OneToMany.class);
if (ann == null) {
ann = f.getAnnotation(OneToMany.class);
if (ann == null)
continue;
}
String mappedBy = ann.mappedBy();
Class<?> tarClass = ann.targetEntity();
if (void.class.isAssignableFrom(tarClass))
tarClass = ClassUtil.getGenericType(f);
List<?> tarList = null;
try {
tarList = (List<?>) tarGetter.invoke(t);
} catch (Exception e) {
throw new DAOException(tarGetter + " invoke exception ", e);
}
if (tarList == null || tarList.size() == 0) {
// 当关联对象为空的时候,删除所有关联对象
ReflectUtil tarRu = new ReflectUtil(tarClass);
if (mappedBy == null || mappedBy.trim().length() == 0) {
for (Field tarObjField : tarRu.getFields()) {
if (!tarObjField.getType().getName().equals(ownClass.getName()))
continue;
Method tarObjFieldGetter = tarRu.getGetter(tarObjField.getName());
if (tarObjFieldGetter == null)
continue;
ManyToOne manyToOne = tarObjField.getAnnotation(ManyToOne.class);
if (manyToOne == null)
manyToOne = tarObjFieldGetter.getAnnotation(ManyToOne.class);
if (manyToOne == null)
continue;
mappedBy = tarObjField.getName();
String fromRefCol = null;
JoinColumn joinCol = tarObjField.getAnnotation(JoinColumn.class);
if (joinCol == null)
joinCol = tarObjFieldGetter.getAnnotation(JoinColumn.class);
if (joinCol != null)
fromRefCol = joinCol.referencedColumnName();
if (fromRefCol == null || fromRefCol.trim().length() == 0)
fromRefCol = ORMConfigBeanUtil.getIdColumn(t);
String fromRefField = ORMConfigBeanUtil.getField(ownClass, fromRefCol);
Method fromRefFieldGetter = ru.getGetter(fromRefField);
if (fromRefFieldGetter == null)
throw new Exception("can not find the 'from ref field field -> " + fromRefField + "' of " + ownClass + " 's getter method");
String fromRefVal = null;
Object _obj = fromRefFieldGetter.invoke(t);
if (_obj != null)
fromRefVal = String.valueOf(_obj);
DAOFactory.getDeleteDAO(dsName).deleteByFieldIsValue(tarClass, new String[] { tarObjField.getName() }, new String[] { fromRefVal });
break;
}
}
} else {
// 当关联对象不为空的时候,删除这些关联对象
for (int i = 0; i < tarList.size(); i++) {
Object tarObj = tarList.get(i);
if (tarObj == null)
continue;
//如果这些对象没有ID值,跳过
Object tarObjIdVal = ORMConfigBeanUtil.getIdVal(tarObj);
if (tarObjIdVal == null)
continue;
ReflectUtil tarRu = new ReflectUtil(tarObj);
if (mappedBy != null && mappedBy.trim().length() > 0) {
Method ownFieldSetter = tarRu.getSetter(mappedBy);
if (ownFieldSetter == null)
continue;
// finished
DAOFactory.getDeleteDAO(dsName).deleteById(tarObj);
} else {
JoinTable joinTable = null;
if (f.isAnnotationPresent(JoinTable.class)) {
joinTable = f.getAnnotation(JoinTable.class);
} else if (tarGetter.isAnnotationPresent(JoinTable.class)) {
joinTable = tarGetter.getAnnotation(JoinTable.class);
} else {
// find ownclass in tarObj fields
for (Field tarObjField : tarRu.getFields()) {
if (!tarObjField.getType().getName().equals(ownClass.getName()))
continue;
Method tarObjFieldGetter = tarRu.getGetter(tarObjField.getName());
if (tarObjFieldGetter == null)
continue;
ManyToOne manyToOne = tarObjField.getAnnotation(ManyToOne.class);
if (manyToOne == null)
manyToOne = tarObjFieldGetter.getAnnotation(ManyToOne.class);
if (manyToOne == null)
continue;
String fromRefCol = null;
JoinColumn joinCol = tarObjField.getAnnotation(JoinColumn.class);
if (joinCol == null)
joinCol = tarObjFieldGetter.getAnnotation(JoinColumn.class);
if (joinCol != null)
fromRefCol = joinCol.referencedColumnName();
if (fromRefCol == null || fromRefCol.trim().length() == 0)
fromRefCol = ORMConfigBeanUtil.getIdColumn(t);
String fromRefField = ORMConfigBeanUtil.getField(ownClass, fromRefCol);
Method fromRefFieldGetter = ru.getGetter(fromRefField);
if (fromRefFieldGetter == null)
throw new Exception("can not find the 'from ref field field -> " + fromRefField + "' of " + ownClass + " 's getter method");
String fromRefVal = null;
Object _obj = fromRefFieldGetter.invoke(t);
if (_obj != null)
fromRefVal = String.valueOf(_obj);
DAOFactory.getDeleteDAO(dsName).deleteByFieldIsValue(tarClass, new String[] { tarObjField.getName() }, new String[] { fromRefVal });
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;
String 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(tarObj);
if (_obj2 == null)
continue;
String toRefVal = String.valueOf(_obj2);
// delete from relTable where from = ? and to = ? ;
String format = "delete from %s where %s = ? and %s = ? ;";
String sql = String.format(format, relTable, from, to);
// finished
DAOFactory.getUpdateDAO(dsName).updateBySQLWithArgs(sql, fromRefVal, toRefVal);
}
}
}
}
}
}
});
}
use of javax.persistence.JoinColumn in project eweb4j-framework by laiweiwei.
the class OneToManyDAO method select.
/**
* 一对多(主从)级联查询
*/
public void select() throws DAOException {
if (this.fields == null || this.fields.size() == 0)
return;
Class<?> ownClass = ru.getObject().getClass();
String fromRefVal = null;
for (Field f : fields) {
Method tarGetter = ru.getGetter(f.getName());
if (tarGetter == null)
continue;
OneToMany ann = tarGetter.getAnnotation(OneToMany.class);
if (ann == null) {
ann = f.getAnnotation(OneToMany.class);
if (ann == null)
continue;
}
OrderBy orderAnn = tarGetter.getAnnotation(OrderBy.class);
if (orderAnn == null)
orderAnn = f.getAnnotation(OrderBy.class);
Class<?> tarClass = ann.targetEntity();
if (void.class.isAssignableFrom(tarClass))
tarClass = ClassUtil.getGenericType(f);
String orderBy = "";
if (orderAnn != null && orderAnn.value().trim().length() > 0)
orderBy = " ORDER BY " + orderAnn.value().replace("t.", tarClass.getSimpleName().toLowerCase() + ".");
String mappedBy = ann.mappedBy();
try {
ReflectUtil tarRu = new ReflectUtil(tarClass);
List<?> tarList = null;
JoinTable joinTable = null;
if (f.isAnnotationPresent(JoinTable.class)) {
joinTable = f.getAnnotation(JoinTable.class);
} else if (tarGetter.isAnnotationPresent(JoinTable.class)) {
joinTable = tarGetter.getAnnotation(JoinTable.class);
}
// 如果用户填写了 JoinTable注解,说明是第三方表建立的关联关系,需要查询第三方表和字段才能获取到targetList
if (joinTable != null) {
JoinColumn[] froms = joinTable.joinColumns();
if (froms == null || froms.length == 0)
continue;
String tarTable = joinTable.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 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 format = "select %s from %s where %s = ? ;";
String sql = String.format(format, ORMConfigBeanUtil.getSelectAllColumn(tarClass), tarTable, from) + orderBy;
// finished
tarList = DAOFactory.getSelectDAO(dsName).selectBySQL(tarClass, sql, fromRefVal);
} else {
// 否则的话按照ManyToOne去查询
// 如果给定了 mappedBy,直接用这个mappedBy来获取filed,否则遍历。
Field mappedField = null;
if (mappedBy != null && mappedBy.trim().length() > 0) {
mappedField = tarRu.getField(mappedBy);
} else {
for (Field field : tarRu.getFields()) {
if (!field.getType().getName().equals(ownClass.getName()))
continue;
mappedField = field;
mappedBy = mappedField.getName();
break;
}
}
if (mappedField == null)
throw new Exception("mapped field of " + tarClass + " not found");
Method tarObjFieldGetter = tarRu.getGetter(mappedBy);
if (tarObjFieldGetter == null)
continue;
ManyToOne manyToOne = mappedField.getAnnotation(ManyToOne.class);
if (manyToOne == null)
manyToOne = tarObjFieldGetter.getAnnotation(ManyToOne.class);
if (manyToOne == null)
continue;
String fromRefCol = null;
JoinColumn joinCol = mappedField.getAnnotation(JoinColumn.class);
if (joinCol == null)
joinCol = tarObjFieldGetter.getAnnotation(JoinColumn.class);
if (joinCol != null)
fromRefCol = joinCol.referencedColumnName();
if (fromRefCol == null || fromRefCol.trim().length() == 0)
fromRefCol = ORMConfigBeanUtil.getIdColumn(t);
String fromRefField = ORMConfigBeanUtil.getField(ownClass, fromRefCol);
Method fromRefFieldGetter = ru.getGetter(fromRefField);
if (fromRefFieldGetter == null)
throw new Exception("can not find the 'from ref field field -> " + fromRefField + "' of " + ownClass + " 's getter method");
Object _obj = fromRefFieldGetter.invoke(t);
if (_obj != null)
fromRefVal = String.valueOf(_obj);
String format = "select %s from %s where %s = ? ;";
String sql = String.format(format, ORMConfigBeanUtil.getSelectAllColumn(tarClass), ORMConfigBeanUtil.getTable(tarClass, true), ORMConfigBeanUtil.getColumn(tarClass, mappedBy)) + orderBy;
// finished
tarList = DAOFactory.getSelectDAO(dsName).selectBySQL(tarClass, sql, fromRefVal);
}
if (tarList == null)
continue;
Method tarSetter = ru.getSetter(f.getName());
if (tarSetter == null)
continue;
tarSetter.invoke(t, tarList);
} catch (Exception e) {
throw new DAOException("", e);
}
}
}
use of javax.persistence.JoinColumn in project eweb4j-framework by laiweiwei.
the class ORMConfigBeanUtil method getColumnsOrFields.
/**
* get columns through fields
*
* @param clazz
* @param fields
* @param type
* 1.getColumns 2.getFields 3.allColumns 4.allFields
*
* @return
*/
private static <T> String[] getColumnsOrFields(T t, String[] strs, int type) {
Class<?> clazz;
if (t instanceof Class) {
clazz = (Class<?>) t;
} else {
clazz = t.getClass();
}
if (!(t instanceof Class) && Map.class.isAssignableFrom(clazz)) {
HashMap<String, Object> map = (HashMap<String, Object>) t;
return (String[]) map.get("columns");
}
if (strs == null)
strs = new String[] { "" };
String[] result = strs.clone();
List<String> list = new ArrayList<String>();
ORMConfigBean ormBean = ORMConfigBeanCache.get(clazz.getName());
if (ormBean == null) {
try {
ReflectUtil ru = new ReflectUtil(clazz);
// String idColumn = getIdColumn(clazz);
for (int i = 0; i < strs.length; i++) {
boolean finished = false;
Field[] _fields = ru.getFields();
for (Field _f : _fields) {
String pName = _f.getName();
JoinColumn jc = _f.getAnnotation(JoinColumn.class);
Column c = _f.getAnnotation(Column.class);
String col = pName;
if (c != null && c.name().trim().length() > 0)
col = c.name();
if (jc != null && jc.name().trim().length() > 0)
col = jc.name();
if (finished)
break;
switch(type) {
case 1:
int dotIndex = strs[i].indexOf(".");
if (dotIndex > 0 && dotIndex < strs[i].length() - 1) {
String[] dots = strs[i].split("\\.");
StringBuilder builder = new StringBuilder();
Class<?> prevCls = null;
for (int j = 0; j < dots.length; j++) {
String dot = dots[j];
Field field = ru.getField(dot);
if (field == null && dot.equals(clazz.getSimpleName().toLowerCase())) {
if (builder.length() > 0)
builder.append(".");
builder.append(dot);
prevCls = clazz;
} else if (field != null) {
if (j == dots.length - 1) {
if (builder.length() > 0)
builder.append(".");
builder.append(ORMConfigBeanUtil.getColumn(prevCls, dot));
} else {
Class<?> cls = ClassUtil.getGenericType(field);
if (cls != null) {
if (ORMConfigBeanCache.get(cls.getName()) != null) {
if (builder.length() > 0)
builder.append(".");
builder.append(cls.getSimpleName().toLowerCase());
prevCls = cls;
ru = new ReflectUtil(cls);
}
}
}
}
}
if (builder.length() > 0) {
result[i] = builder.toString();
finished = true;
break;
}
}
if (pName.equals(strs[i])) {
result[i] = col;
finished = true;
}
break;
case 2:
if (col.equals(strs[i])) {
result[i] = pName;
finished = true;
}
break;
case 3:
list.add(col);
break;
case 4:
list.add(pName);
}
}
}
} catch (Throwable e) {
}
} else {
try {
ReflectUtil ru = new ReflectUtil(clazz);
// String idColumn = getIdColumn(clazz);
for (int i = 0; i < strs.length; i++) {
boolean finished = false;
List<Property> properties = ormBean.getProperty();
for (Property p : properties) {
if (finished)
break;
switch(type) {
case 1:
int dotIndex = strs[i].indexOf(".");
if (dotIndex > 0 && dotIndex < strs[i].length() - 1) {
String[] dots = strs[i].split("\\.");
StringBuilder builder = new StringBuilder();
Class<?> prevCls = null;
for (int j = 0; j < dots.length; j++) {
String dot = dots[j];
Field field = ru.getField(dot);
if (field == null && dot.equals(clazz.getSimpleName().toLowerCase())) {
if (builder.length() > 0)
builder.append(".");
builder.append(dot);
prevCls = clazz;
} else if (field != null) {
if (j == dots.length - 1) {
if (builder.length() > 0)
builder.append(".");
builder.append(ORMConfigBeanUtil.getColumn(prevCls, dot));
} else {
Class<?> cls = ClassUtil.getGenericType(field);
if (cls != null) {
if (ORMConfigBeanCache.get(cls.getName()) != null) {
if (builder.length() > 0)
builder.append(".");
builder.append(cls.getSimpleName().toLowerCase());
prevCls = cls;
ru = new ReflectUtil(cls);
}
}
}
}
}
if (builder.length() > 0) {
result[i] = builder.toString();
finished = true;
break;
}
}
if (p.getName().equals(strs[i])) {
result[i] = p.getColumn();
finished = true;
}
break;
case 2:
if (p.getColumn().equals(strs[i])) {
result[i] = p.getName();
finished = true;
}
break;
case 3:
list.add(p.getColumn());
break;
case 4:
list.add(p.getName());
}
}
}
} catch (Exception e) {
}
}
return list.isEmpty() ? result : list.toArray(new String[] {});
}
use of javax.persistence.JoinColumn in project eweb4j-framework by laiweiwei.
the class InsertSqlCreator method create.
public Sql[] create(String condition) throws SqlCreateException {
Sql[] sqls = new Sql[ts.length];
for (int index = 0; index < ts.length; ++index) {
String table = null;
StringBuilder columnSB = new StringBuilder();
StringBuilder valueSB = new StringBuilder();
T t = ts[index];
Class<?> clazz = t.getClass();
String[] fields;
String[] columns;
String idColumn;
Object[] values = null;
sqls[index] = new Sql();
HashMap<String, Object> map = null;
if (Map.class.isAssignableFrom(clazz)) {
map = (HashMap<String, Object>) t;
table = String.valueOf(map.get("table"));
idColumn = String.valueOf(map.get("idColumn"));
if (idColumn == null)
idColumn = "id";
fields = (String[]) map.get("columns");
columns = fields;
values = (Object[]) map.get("values");
} else {
table = ORMConfigBeanUtil.getTable(clazz, false);
idColumn = ORMConfigBeanUtil.getIdColumn(t.getClass());
fields = ORMConfigBeanUtil.getFields(clazz);
columns = ORMConfigBeanUtil.getColumns(clazz);
}
ReflectUtil ru = new ReflectUtil(t);
for (int i = 0; i < columns.length; i++) {
String column = columns[i];
Object value = null;
if (map != null && values != null) {
value = values[i];
} else {
String name = fields[i];
Method getter = ru.getGetter(name);
if (getter == null)
continue;
Object _value = null;
try {
_value = getter.invoke(t);
if (_value == null)
continue;
if (ClassUtil.isPojo(_value.getClass())) {
Field f = ru.getField(name);
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;
}
} catch (Exception e) {
throw new SqlCreateException(getter + " invoke exception " + e.toString(), e);
}
}
// id 字段不允许插入表中
if (idColumn != null && idColumn.equalsIgnoreCase(column))
continue;
if (columnSB.length() > 0)
columnSB.append(",");
columnSB.append(column);
if (valueSB.length() > 0)
valueSB.append(",");
// valueSB.append("'").append(value).append("'");
valueSB.append("?");
sqls[index].args.add(value);
}
String format = "INSERT INTO ${table}(${columns}) VALUES(${values}) ${condition} ;";
format = format.replace("${table}", table);
format = format.replace("${columns}", columnSB.toString());
format = format.replace("${values}", valueSB.toString());
if (condition != null)
format = format.replace("${condition}", " WHERE " + condition);
else
format = format.replace("${condition} ", "");
sqls[index].sql = format;
}
return sqls;
}
use of javax.persistence.JoinColumn in project eweb4j-framework by laiweiwei.
the class InsertSqlCreator method createByFieldsIsValues.
public Sql[] createByFieldsIsValues(String[][] fields, Object[][] values) throws SqlCreateException {
Sql[] sqls = new Sql[ts.length];
for (int i = 0; i < ts.length; ++i) {
T t = ts[i];
ReflectUtil ru = new ReflectUtil(t);
Class<?> clazz = t.getClass();
String table = ORMConfigBeanUtil.getTable(clazz, false);
StringBuilder columnSB = new StringBuilder();
StringBuilder valueSB = new StringBuilder();
sqls[i] = new Sql();
for (int j = 0; j < fields[i].length; ++j) {
String name = fields[i][j];
Object _value = null;
Object value = null;
if (values == null) {
Method getter = null;
try {
getter = ru.getGetter(name);
if (getter == null)
continue;
_value = getter.invoke(t);
if (_value == null)
continue;
if (ClassUtil.isPojo(_value.getClass())) {
Field f = ru.getField(fields[i][j]);
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;
}
} catch (Exception e) {
throw new SqlCreateException(getter + " invoke exception " + e.toString(), e);
}
} else {
value = values[i][j];
}
String column = ORMConfigBeanUtil.getColumn(clazz, name);
if (valueSB.length() > 0) {
columnSB.append(",");
valueSB.append(",");
}
columnSB.append(column);
// valueSB.append("'").append(value).append("'");
valueSB.append("?");
sqls[i].args.add(value);
}
sqls[i].sql = String.format("INSERT INTO %s(%s) VALUES(%s) ;", table, columnSB.toString(), valueSB.toString());
}
return sqls;
}
Aggregations