use of javax.persistence.JoinColumn in project hibernate-orm by hibernate.
the class ColumnsBuilder method extractMetadata.
public ColumnsBuilder extractMetadata() {
columns = null;
joinColumns = buildExplicitJoinColumns(property, inferredData);
if (property.isAnnotationPresent(Column.class) || property.isAnnotationPresent(Formula.class)) {
Column ann = property.getAnnotation(Column.class);
Formula formulaAnn = property.getAnnotation(Formula.class);
columns = Ejb3Column.buildColumnFromAnnotation(new Column[] { ann }, formulaAnn, nullability, propertyHolder, inferredData, entityBinder.getSecondaryTables(), buildingContext);
} else if (property.isAnnotationPresent(Columns.class)) {
Columns anns = property.getAnnotation(Columns.class);
columns = Ejb3Column.buildColumnFromAnnotation(anns.columns(), null, nullability, propertyHolder, inferredData, entityBinder.getSecondaryTables(), buildingContext);
}
//set default values if needed
if (joinColumns == null && (property.isAnnotationPresent(ManyToOne.class) || property.isAnnotationPresent(OneToOne.class))) {
joinColumns = buildDefaultJoinColumnsForXToOne(property, inferredData);
} else if (joinColumns == null && (property.isAnnotationPresent(OneToMany.class) || property.isAnnotationPresent(ElementCollection.class))) {
OneToMany oneToMany = property.getAnnotation(OneToMany.class);
String mappedBy = oneToMany != null ? oneToMany.mappedBy() : "";
joinColumns = Ejb3JoinColumn.buildJoinColumns(null, mappedBy, entityBinder.getSecondaryTables(), propertyHolder, inferredData.getPropertyName(), buildingContext);
} else if (joinColumns == null && property.isAnnotationPresent(org.hibernate.annotations.Any.class)) {
throw new AnnotationException("@Any requires an explicit @JoinColumn(s): " + BinderHelper.getPath(propertyHolder, inferredData));
}
if (columns == null && !property.isAnnotationPresent(ManyToMany.class)) {
//useful for collection of embedded elements
columns = Ejb3Column.buildColumnFromAnnotation(null, null, nullability, propertyHolder, inferredData, entityBinder.getSecondaryTables(), buildingContext);
}
if (nullability == Nullability.FORCED_NOT_NULL) {
//force columns to not null
for (Ejb3Column col : columns) {
col.forceNotNull();
}
}
return this;
}
use of javax.persistence.JoinColumn in project hibernate-orm by hibernate.
the class AnnotationBinder method addProperty.
private static int addProperty(PropertyContainer propertyContainer, XProperty property, List<PropertyData> inFlightPropertyDataList, MetadataBuildingContext context) {
// and if so, skip it..
for (PropertyData propertyData : inFlightPropertyDataList) {
if (propertyData.getPropertyName().equals(property.getName())) {
// EARLY EXIT!!!
return 0;
}
}
final XClass declaringClass = propertyContainer.getDeclaringClass();
final XClass entity = propertyContainer.getEntityAtStake();
int idPropertyCounter = 0;
PropertyData propertyAnnotatedElement = new PropertyInferredData(declaringClass, property, propertyContainer.getClassLevelAccessType().getType(), context.getBuildingOptions().getReflectionManager());
/*
* put element annotated by @Id in front
* since it has to be parsed beforeQuery any association by Hibernate
*/
final XAnnotatedElement element = propertyAnnotatedElement.getProperty();
if (element.isAnnotationPresent(Id.class) || element.isAnnotationPresent(EmbeddedId.class)) {
inFlightPropertyDataList.add(0, propertyAnnotatedElement);
/**
* The property must be put in hibernate.properties as it's a system wide property. Fixable?
* TODO support true/false/default on the property instead of present / not present
* TODO is @Column mandatory?
* TODO add method support
*/
if (context.getBuildingOptions().isSpecjProprietarySyntaxEnabled()) {
if (element.isAnnotationPresent(Id.class) && element.isAnnotationPresent(Column.class)) {
String columnName = element.getAnnotation(Column.class).name();
for (XProperty prop : declaringClass.getDeclaredProperties(AccessType.FIELD.getType())) {
if (!prop.isAnnotationPresent(MapsId.class)) {
/**
* The detection of a configured individual JoinColumn differs between Annotation
* and XML configuration processing.
*/
boolean isRequiredAnnotationPresent = false;
JoinColumns groupAnnotation = prop.getAnnotation(JoinColumns.class);
if ((prop.isAnnotationPresent(JoinColumn.class) && prop.getAnnotation(JoinColumn.class).name().equals(columnName))) {
isRequiredAnnotationPresent = true;
} else if (prop.isAnnotationPresent(JoinColumns.class)) {
for (JoinColumn columnAnnotation : groupAnnotation.value()) {
if (columnName.equals(columnAnnotation.name())) {
isRequiredAnnotationPresent = true;
break;
}
}
}
if (isRequiredAnnotationPresent) {
//create a PropertyData fpr the specJ property holding the mapping
PropertyData specJPropertyData = new PropertyInferredData(declaringClass, //same dec
prop, // the actual @XToOne property
propertyContainer.getClassLevelAccessType().getType(), //TODO we should get the right accessor but the same as id would do
context.getBuildingOptions().getReflectionManager());
context.getMetadataCollector().addPropertyAnnotatedWithMapsIdSpecj(entity, specJPropertyData, element.toString());
}
}
}
}
}
if (element.isAnnotationPresent(ManyToOne.class) || element.isAnnotationPresent(OneToOne.class)) {
context.getMetadataCollector().addToOneAndIdProperty(entity, propertyAnnotatedElement);
}
idPropertyCounter++;
} else {
inFlightPropertyDataList.add(propertyAnnotatedElement);
}
if (element.isAnnotationPresent(MapsId.class)) {
context.getMetadataCollector().addPropertyAnnotatedWithMapsId(entity, propertyAnnotatedElement);
}
return idPropertyCounter;
}
use of javax.persistence.JoinColumn 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);
}
}
}
use of javax.persistence.JoinColumn 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);
}
}
}
use of javax.persistence.JoinColumn 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);
}
}
}
Aggregations