use of javax.persistence.ManyToOne in project orientdb by orientechnologies.
the class OObjectEntitySerializer method getSpecifiedLinkedType.
public static Class<?> getSpecifiedLinkedType(final Field f) {
final ManyToOne m = f.getAnnotation(ManyToOne.class);
if (m != null && !m.targetEntity().equals(void.class))
return m.targetEntity();
final OneToOne m2 = f.getAnnotation(OneToOne.class);
if (m2 != null && !m2.targetEntity().equals(void.class))
return m2.targetEntity();
return null;
}
use of javax.persistence.ManyToOne 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);
}
}
}
use of javax.persistence.ManyToOne 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;
}
use of javax.persistence.ManyToOne 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;
}
use of javax.persistence.ManyToOne in project simplejpa by appoxy.
the class Save method persistOnly.
protected void persistOnly(Object o, String id) throws AmazonClientException, IllegalAccessException, InvocationTargetException, IOException {
long start = System.currentTimeMillis();
em.invokeEntityListener(o, newObject ? PrePersist.class : PreUpdate.class);
AnnotationInfo ai = em.getFactory().getAnnotationManager().getAnnotationInfo(o);
UpdateCondition expected = null;
PersistentProperty versionField = null;
Long nextVersion = -1L;
String domainName;
if (ai.getRootClass() != null) {
domainName = em.getOrCreateDomain(ai.getRootClass());
} else {
domainName = em.getOrCreateDomain(o.getClass());
}
// Item item = DomainHelper.findItemById(this.em.getSimpleDb(),
// domainName, id);
// now set attributes
List<ReplaceableAttribute> attsToPut = new ArrayList<ReplaceableAttribute>();
List<Attribute> attsToDelete = new ArrayList<Attribute>();
if (ai.getDiscriminatorValue() != null) {
attsToPut.add(new ReplaceableAttribute(EntityManagerFactoryImpl.DTYPE, ai.getDiscriminatorValue(), true));
}
LazyInterceptor interceptor = null;
if (o instanceof Factory) {
Factory factory = (Factory) o;
/*
* for (Callback callback2 : factory.getCallbacks()) {
* if(logger.isLoggable(Level.FINER)) logger.finer("callback=" +
* callback2); if (callback2 instanceof LazyInterceptor) {
* interceptor = (LazyInterceptor) callback2; } }
*/
interceptor = (LazyInterceptor) factory.getCallback(0);
}
for (PersistentProperty field : ai.getPersistentProperties()) {
Object ob = field.getProperty(o);
String columnName = field.getColumnName();
if (ob == null) {
attsToDelete.add(new Attribute(columnName, null));
continue;
}
if (field.isForeignKeyRelationship()) {
// store the id of this object
if (Collection.class.isAssignableFrom(field.getRawClass())) {
for (Object each : (Collection) ob) {
String id2 = em.getId(each);
attsToPut.add(new ReplaceableAttribute(columnName, id2, true));
}
} else {
String id2 = em.getId(ob);
attsToPut.add(new ReplaceableAttribute(columnName, id2, true));
/* check if we should persist this */
boolean persistRelationship = false;
ManyToOne a = field.getGetter().getAnnotation(ManyToOne.class);
if (a != null && null != a.cascade()) {
CascadeType[] cascadeType = a.cascade();
for (CascadeType type : cascadeType) {
if (CascadeType.ALL == type || CascadeType.PERSIST == type) {
persistRelationship = true;
}
}
}
if (persistRelationship) {
em.persist(ob);
}
}
} else if (field.isVersioned()) {
Long curVersion = Long.parseLong("" + ob);
nextVersion = (1 + curVersion);
attsToPut.add(new ReplaceableAttribute(columnName, em.padOrConvertIfRequired(nextVersion), true));
if (curVersion > 0) {
expected = new UpdateCondition(columnName, em.padOrConvertIfRequired(curVersion), true);
} else {
expected = new UpdateCondition().withName(columnName).withExists(false);
}
versionField = field;
} else if (field.isInverseRelationship()) {
// FORCING BI-DIRECTIONAL RIGHT NOW SO JUST IGNORE
// ... except for cascading persistence down to all items in the
// OneToMany collection
/* check if we should persist this */
boolean persistRelationship = false;
OneToMany a = field.getGetter().getAnnotation(OneToMany.class);
CascadeType[] cascadeType = a.cascade();
for (CascadeType type : cascadeType) {
if (CascadeType.ALL == type || CascadeType.PERSIST == type) {
persistRelationship = true;
}
}
if (persistRelationship) {
if (ob instanceof Collection) {
// shouldn't it?
for (Object _item : (Collection) ob) {
// persist each item in the collection
em.persist(_item);
}
}
}
} else if (field.isLob()) {
// store in s3
AmazonS3 s3 = null;
// todo: need to make sure we only store to S3 if it's changed,
// too slow.
logger.fine("putting lob to s3");
long start3 = System.currentTimeMillis();
s3 = em.getS3Service();
String bucketName = em.getS3BucketName();
String s3ObjectId = id + "-" + field.getFieldName();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bos);
out.writeObject(ob);
byte[] contentBytes = bos.toByteArray();
out.close();
InputStream input = new ByteArrayInputStream(contentBytes);
s3.putObject(bucketName, s3ObjectId, input, null);
em.statsS3Put(System.currentTimeMillis() - start3);
logger.finer("setting lobkeyattribute=" + columnName + " - " + s3ObjectId);
attsToPut.add(new ReplaceableAttribute(columnName, s3ObjectId, true));
} else if (field.getEnumType() != null) {
String toSet = getEnumValue(field, o);
attsToPut.add(new ReplaceableAttribute(columnName, toSet, true));
} else if (field.isId()) {
continue;
} else if (Collection.class.isInstance(ob)) {
for (Object each : ((Collection) ob)) {
String toSet = each != null ? em.padOrConvertIfRequired(each) : "";
// todo: throw an exception if this is going to exceed
// maximum size, suggest using @Lob
attsToPut.add(new ReplaceableAttribute(columnName, toSet, true));
}
} else {
String toSet = ob != null ? em.padOrConvertIfRequired(ob) : "";
// todo: throw an exception if this is going to exceed maximum
// size, suggest using @Lob
attsToPut.add(new ReplaceableAttribute(columnName, toSet, true));
}
}
// Now finally send it for storage (If have attributes to add)
long start2 = System.currentTimeMillis();
long duration2;
if (!attsToPut.isEmpty()) {
this.em.getSimpleDb().putAttributes(new PutAttributesRequest().withDomainName(domainName).withItemName(id).withAttributes(attsToPut).withExpected(expected));
duration2 = System.currentTimeMillis() - start2;
if (logger.isLoggable(Level.FINE))
logger.fine("putAttributes time=" + (duration2));
em.statsAttsPut(attsToPut.size(), duration2);
if (null != versionField)
versionField.setProperty(o, nextVersion);
}
/*
* Check for nulled attributes so we can send a delete call. Don't
* delete attributes if this is a new object AND don't delete atts if
* it's not dirty AND don't delete if no nulls were set (nulledField on
* LazyInterceptor)
*/
if (interceptor != null) {
if (interceptor.getNulledFields() != null && interceptor.getNulledFields().size() > 0) {
List<Attribute> attsToDelete2 = new ArrayList<Attribute>();
for (String s : interceptor.getNulledFields().keySet()) {
String columnName = ai.getPersistentProperty(s).getColumnName();
attsToDelete2.add(new Attribute(columnName, null));
}
start2 = System.currentTimeMillis();
this.em.getSimpleDb().deleteAttributes(new DeleteAttributesRequest().withDomainName(domainName).withItemName(id).withAttributes(attsToDelete2));
// todo: what about lobs? need to delete from s3
duration2 = System.currentTimeMillis() - start2;
logger.fine("deleteAttributes time=" + (duration2));
em.statsAttsDeleted(attsToDelete2.size(), duration2);
} else {
logger.fine("deleteAttributes time= no nulled fields, nothing to delete.");
}
} else {
if (!newObject && attsToDelete.size() > 0) {
// not enhanced, but still have to deal with deleted attributes
start2 = System.currentTimeMillis();
// for (ItemAttribute itemAttribute : attsToDelete) {
// System.out.println("itemAttr=" + itemAttribute.getName() +
// ": " + itemAttribute.getValue());
// }
this.em.getSimpleDb().deleteAttributes(new DeleteAttributesRequest().withDomainName(domainName).withItemName(id).withAttributes(attsToDelete));
// todo: what about lobs? need to delete from s3
duration2 = System.currentTimeMillis() - start2;
logger.fine("deleteAttributes time=" + (duration2));
em.statsAttsDeleted(attsToDelete.size(), duration2);
}
}
if (interceptor != null) {
// reset the interceptor since we're all synced with the db now
interceptor.reset();
}
em.invokeEntityListener(o, newObject ? PostPersist.class : PostUpdate.class);
if (logger.isLoggable(Level.FINE))
logger.fine("persistOnly time=" + (System.currentTimeMillis() - start));
}
Aggregations