use of javax.persistence.Entity in project eweb4j-framework by laiweiwei.
the class ORMConfigBeanWriter method write.
/**
* 将某个Class写入到目标xml文件中
*
* @param filePath
* 文件相对路径
* @param clazzs
* @return
*/
public static String write(String filePath, Class<?>... clazzs) {
String error = null;
File file = new File(ConfigConstant.CONFIG_BASE_PATH + filePath);
if (filePath != null && clazzs != null && clazzs.length > 0) {
List<ORMConfigBean> ormList = new ArrayList<ORMConfigBean>();
try {
for (int i = 0; i < clazzs.length; ++i) {
Class<?> clazz = clazzs[i];
String clsName = clazz.getSimpleName();
Entity entity = clazz.getAnnotation(Entity.class);
if (entity == null && !clsName.endsWith("PO") && !clsName.endsWith("POJO") && !clsName.endsWith("Entity") && !clsName.endsWith("Model")) {
return null;
}
Table tableAnn = clazz.getAnnotation(Table.class);
String table = tableAnn == null ? "" : tableAnn.name();
table = "".equals(table.trim()) ? clsName : table;
ORMConfigBean ormBean = new ORMConfigBean();
ormBean.setClazz(clazz.getName());
ormBean.setId(clazz.getSimpleName());
ormBean.setTable(table);
ReflectUtil ru;
ru = new ReflectUtil(clazz);
List<Property> pList = new ArrayList<Property>();
for (Field f : ru.getFields()) {
String name = f.getName();
Method getter = ru.getGetter(name);
Column colAnn = getter.getAnnotation(Column.class);
if (colAnn == null) {
colAnn = f.getAnnotation(Column.class);
if (colAnn == null)
continue;
}
Id idAnn = f.getAnnotation(Id.class);
if (idAnn == null) {
idAnn = getter.getAnnotation(Id.class);
if (idAnn == null)
continue;
}
Property p = new Property();
p.setAutoIncrement("1");
p.setPk("1");
Pk pkAnn = f.getAnnotation(Pk.class);
if (pkAnn != null) {
p.setPk("1");
}
String column = colAnn.name();
column = "".equals(column.trim()) ? name : column;
p.setName(name);
p.setColumn(column);
p.setType(f.getType().getName());
pList.add(p);
}
ormBean.setProperty(pList);
ormList.add(ormBean);
}
BeanXMLUtil.getBeanXMLWriter(file, ormList).write();
} catch (Exception e) {
error = e.getMessage();
e.printStackTrace();
}
} else {
error = "Class参数不能为空";
}
return error;
}
use of javax.persistence.Entity in project eweb4j-framework by laiweiwei.
the class CascadeDAO method cascade.
/**
* 级联
*
* @param <T>
* @param t
* @param fieldNames
* 对指定属性名进行级联操作,当为null时,对所有属性进行级联操作
* @param type
* 1表示级联查询,2表示级联删除,3表示级联插入,4表示级联更新
* @param delType
* @
*/
public <T> void cascade(T[] ts, String[] fieldNames, int type, long newIdVal) {
// 首先判断给定的pojo是否是一个持久化对象
if (ts == null || ts.length == 0) {
return;
}
for (T t : ts) {
if (t == null)
continue;
Class<?> clazz = t.getClass();
String clsName = clazz.getSimpleName();
Entity entity = clazz.getAnnotation(Entity.class);
if (entity == null && !clsName.endsWith("PO") && !clsName.endsWith("POJO") && !clsName.endsWith("Entity") && !clsName.endsWith("Model")) {
return;
}
ReflectUtil ru = new ReflectUtil(t);
Field[] fields = null;
if (fieldNames == null || fieldNames.length == 0) {
fields = ru.getFields();
} else {
List<Field> fieldList = new ArrayList<Field>();
for (String n : fieldNames) {
if (n != null && !"".equals(n.trim())) {
Field f = ru.getField(n);
if (f != null) {
fieldList.add(f);
}
}
}
if (fieldList.size() > 0) {
fields = fieldList.toArray(new Field[] {});
}
}
if (fields != null) {
List<Field> oneList = new ArrayList<Field>();
List<Field> manyList = new ArrayList<Field>();
List<Field> manyManyList = new ArrayList<Field>();
for (Field f : fields) {
Method getter = ru.getGetter(f.getName());
if (f.isAnnotationPresent(OneToMany.class) || (getter != null && getter.isAnnotationPresent(OneToMany.class))) {
manyList.add(f);
} else if (f.isAnnotationPresent(ManyToOne.class) || (getter != null && getter.isAnnotationPresent(ManyToOne.class))) {
oneList.add(f);
} else if (f.isAnnotationPresent(OneToOne.class) || (getter != null && getter.isAnnotationPresent(OneToOne.class))) {
oneList.add(f);
} else if (f.isAnnotationPresent(ManyToMany.class) || (getter != null && getter.isAnnotationPresent(ManyToMany.class))) {
manyManyList.add(f);
}
}
this.manyToMany.init(t, manyManyList);
this.oneToMany.init(t, manyList);
this.oneToOne.init(t, oneList);
switch(type) {
case CascadeType.SELECT:
this.manyToMany.select();
this.oneToMany.select();
this.oneToOne.select();
break;
case CascadeType.DELETE:
this.manyToMany.delete();
this.oneToMany.delete();
break;
case CascadeType.INSERT:
this.manyToMany.insert();
this.oneToMany.insert();
break;
case CascadeType.UPDATE:
this.oneToMany.update(newIdVal);
this.manyToMany.update(newIdVal);
break;
}
}
}
}
use of javax.persistence.Entity in project simplejpa by appoxy.
the class AnnotationTests method findAnnotations.
@Test
public void findAnnotations() throws IOException {
// scan java.class.path
URL[] urls = ClasspathUrlFinder.findClassPaths();
AnnotationDB db = new AnnotationDB();
db.scanArchives(urls);
Set<String> entities = db.getAnnotationIndex().get(Entity.class.getName());
for (String entity : entities) {
System.out.println("entity=" + entity);
}
}
use of javax.persistence.Entity in project simplejpa by appoxy.
the class AnnotationManager method putAnnotationInfo.
/**
* Gets all the annotation info for a particular class and puts it in our annotation info cache.
*
* @param c
* @return
*/
public AnnotationInfo putAnnotationInfo(Class c) {
{
Entity entity = (Entity) c.getAnnotation(Entity.class);
if (entity == null) {
throw new PersistenceException("Class not marked as an @Entity: " + c.getName());
}
}
AnnotationInfo ai = new AnnotationInfo();
ai.setClassAnnotations(c.getAnnotations());
ai.setMainClass(c);
Class superClass = c;
Class rootClass = null;
while ((superClass = superClass.getSuperclass()) != null) {
MappedSuperclass mappedSuperclass = (MappedSuperclass) superClass.getAnnotation(MappedSuperclass.class);
Entity entity = (Entity) superClass.getAnnotation(Entity.class);
Inheritance inheritance = (Inheritance) superClass.getAnnotation(Inheritance.class);
if (mappedSuperclass != null || entity != null) {
putProperties(ai, superClass);
putMethods(ai, superClass);
if (entity != null) {
rootClass = superClass;
}
putEntityListeners(ai, superClass);
}
}
if (rootClass != null) {
ai.setRootClass(rootClass);
DiscriminatorValue dv = (DiscriminatorValue) c.getAnnotation(DiscriminatorValue.class);
String discriminatorValue;
if (dv != null) {
discriminatorValue = dv.value();
if (discriminatorValue == null) {
throw new PersistenceException("You must specify a value= for @DiscriminatorValue on " + c.getName());
}
} else {
discriminatorValue = c.getSimpleName();
}
ai.setDiscriminatorValue(discriminatorValue);
discriminatorMap.put(discriminatorValue, ai);
} else {
ai.setRootClass(c);
}
putTableDeclaration(ai, c);
putProperties(ai, c);
putMethods(ai, c);
if (ai.getIdMethod() == null) {
throw new PersistenceException("No ID method specified for: " + c.getName());
}
putEntityListeners(ai, c);
getAnnotationMap().put(c.getName(), ai);
return ai;
}
use of javax.persistence.Entity in project hibernate-orm by hibernate.
the class AnnotationBinder method bindClass.
/**
* Bind a class having JSR175 annotations. Subclasses <b>have to</b> be bound afterQuery its parent class.
*
* @param clazzToProcess entity to bind as {@code XClass} instance
* @param inheritanceStatePerClass Meta data about the inheritance relationships for all mapped classes
*
* @throws MappingException in case there is an configuration error
*/
public static void bindClass(XClass clazzToProcess, Map<XClass, InheritanceState> inheritanceStatePerClass, MetadataBuildingContext context) throws MappingException {
//@Entity and @MappedSuperclass on the same class leads to a NPE down the road
if (clazzToProcess.isAnnotationPresent(Entity.class) && clazzToProcess.isAnnotationPresent(MappedSuperclass.class)) {
throw new AnnotationException("An entity cannot be annotated with both @Entity and @MappedSuperclass: " + clazzToProcess.getName());
}
//TODO: be more strict with secondarytable allowance (not for ids, not for secondary table join columns etc)
InheritanceState inheritanceState = inheritanceStatePerClass.get(clazzToProcess);
AnnotatedClassType classType = context.getMetadataCollector().getClassType(clazzToProcess);
//Queries declared in MappedSuperclass should be usable in Subclasses
if (AnnotatedClassType.EMBEDDABLE_SUPERCLASS.equals(classType)) {
bindQueries(clazzToProcess, context);
bindTypeDefs(clazzToProcess, context);
bindFilterDefs(clazzToProcess, context);
}
if (!isEntityClassType(clazzToProcess, classType)) {
return;
}
if (LOG.isDebugEnabled()) {
LOG.debugf("Binding entity from annotated class: %s", clazzToProcess.getName());
}
PersistentClass superEntity = getSuperEntity(clazzToProcess, inheritanceStatePerClass, context, inheritanceState);
PersistentClass persistentClass = makePersistentClass(inheritanceState, superEntity, context);
Entity entityAnn = clazzToProcess.getAnnotation(Entity.class);
org.hibernate.annotations.Entity hibEntityAnn = clazzToProcess.getAnnotation(org.hibernate.annotations.Entity.class);
EntityBinder entityBinder = new EntityBinder(entityAnn, hibEntityAnn, clazzToProcess, persistentClass, context);
entityBinder.setInheritanceState(inheritanceState);
bindQueries(clazzToProcess, context);
bindFilterDefs(clazzToProcess, context);
bindTypeDefs(clazzToProcess, context);
bindFetchProfiles(clazzToProcess, context);
BinderHelper.bindAnyMetaDefs(clazzToProcess, context);
String schema = "";
//might be no @Table annotation on the annotated class
String table = "";
String catalog = "";
List<UniqueConstraintHolder> uniqueConstraints = new ArrayList<UniqueConstraintHolder>();
javax.persistence.Table tabAnn = null;
if (clazzToProcess.isAnnotationPresent(javax.persistence.Table.class)) {
tabAnn = clazzToProcess.getAnnotation(javax.persistence.Table.class);
table = tabAnn.name();
schema = tabAnn.schema();
catalog = tabAnn.catalog();
uniqueConstraints = TableBinder.buildUniqueConstraintHolders(tabAnn.uniqueConstraints());
}
Ejb3JoinColumn[] inheritanceJoinedColumns = makeInheritanceJoinColumns(clazzToProcess, context, inheritanceState, superEntity);
final Ejb3DiscriminatorColumn discriminatorColumn;
if (InheritanceType.SINGLE_TABLE.equals(inheritanceState.getType())) {
discriminatorColumn = processSingleTableDiscriminatorProperties(clazzToProcess, context, inheritanceState, entityBinder);
} else if (InheritanceType.JOINED.equals(inheritanceState.getType())) {
discriminatorColumn = processJoinedDiscriminatorProperties(clazzToProcess, context, inheritanceState, entityBinder);
} else {
discriminatorColumn = null;
}
entityBinder.setProxy(clazzToProcess.getAnnotation(Proxy.class));
entityBinder.setBatchSize(clazzToProcess.getAnnotation(BatchSize.class));
entityBinder.setWhere(clazzToProcess.getAnnotation(Where.class));
entityBinder.setCache(determineCacheSettings(clazzToProcess, context));
entityBinder.setNaturalIdCache(clazzToProcess, clazzToProcess.getAnnotation(NaturalIdCache.class));
bindFilters(clazzToProcess, entityBinder, context);
entityBinder.bindEntity();
if (inheritanceState.hasTable()) {
Check checkAnn = clazzToProcess.getAnnotation(Check.class);
String constraints = checkAnn == null ? null : checkAnn.constraints();
EntityTableXref denormalizedTableXref = inheritanceState.hasDenormalizedTable() ? context.getMetadataCollector().getEntityTableXref(superEntity.getEntityName()) : null;
entityBinder.bindTable(schema, catalog, table, uniqueConstraints, constraints, denormalizedTableXref);
} else {
if (clazzToProcess.isAnnotationPresent(Table.class)) {
LOG.invalidTableAnnotation(clazzToProcess.getName());
}
if (inheritanceState.getType() == InheritanceType.SINGLE_TABLE) {
// we at least need to properly set up the EntityTableXref
entityBinder.bindTableForDiscriminatedSubclass(context.getMetadataCollector().getEntityTableXref(superEntity.getEntityName()));
}
}
PropertyHolder propertyHolder = PropertyHolderBuilder.buildPropertyHolder(clazzToProcess, persistentClass, entityBinder, context, inheritanceStatePerClass);
javax.persistence.SecondaryTable secTabAnn = clazzToProcess.getAnnotation(javax.persistence.SecondaryTable.class);
javax.persistence.SecondaryTables secTabsAnn = clazzToProcess.getAnnotation(javax.persistence.SecondaryTables.class);
entityBinder.firstLevelSecondaryTablesBinding(secTabAnn, secTabsAnn);
OnDelete onDeleteAnn = clazzToProcess.getAnnotation(OnDelete.class);
boolean onDeleteAppropriate = false;
// todo : sucks that this is separate from RootClass distinction
final boolean isInheritanceRoot = !inheritanceState.hasParents();
final boolean hasSubclasses = inheritanceState.hasSiblings();
if (InheritanceType.JOINED.equals(inheritanceState.getType())) {
if (inheritanceState.hasParents()) {
onDeleteAppropriate = true;
final JoinedSubclass jsc = (JoinedSubclass) persistentClass;
SimpleValue key = new DependantValue(context.getMetadataCollector(), jsc.getTable(), jsc.getIdentifier());
jsc.setKey(key);
ForeignKey fk = clazzToProcess.getAnnotation(ForeignKey.class);
if (fk != null && !BinderHelper.isEmptyAnnotationValue(fk.name())) {
key.setForeignKeyName(fk.name());
} else {
final PrimaryKeyJoinColumn pkJoinColumn = clazzToProcess.getAnnotation(PrimaryKeyJoinColumn.class);
final PrimaryKeyJoinColumns pkJoinColumns = clazzToProcess.getAnnotation(PrimaryKeyJoinColumns.class);
if (pkJoinColumns != null && pkJoinColumns.foreignKey().value() == ConstraintMode.NO_CONSTRAINT) {
// don't apply a constraint based on ConstraintMode
key.setForeignKeyName("none");
} else if (pkJoinColumns != null && !StringHelper.isEmpty(pkJoinColumns.foreignKey().name())) {
key.setForeignKeyName(pkJoinColumns.foreignKey().name());
} else if (pkJoinColumn != null && pkJoinColumn.foreignKey().value() == ConstraintMode.NO_CONSTRAINT) {
// don't apply a constraint based on ConstraintMode
key.setForeignKeyName("none");
} else if (pkJoinColumn != null && !StringHelper.isEmpty(pkJoinColumn.foreignKey().name())) {
key.setForeignKeyName(pkJoinColumn.foreignKey().name());
}
}
if (onDeleteAnn != null) {
key.setCascadeDeleteEnabled(OnDeleteAction.CASCADE.equals(onDeleteAnn.action()));
} else {
key.setCascadeDeleteEnabled(false);
}
//we are never in a second pass at that stage, so queue it
context.getMetadataCollector().addSecondPass(new JoinedSubclassFkSecondPass(jsc, inheritanceJoinedColumns, key, context));
context.getMetadataCollector().addSecondPass(new CreateKeySecondPass(jsc));
}
if (isInheritanceRoot) {
// (it is perfectly valid for joined subclasses to not have discriminators).
if (discriminatorColumn != null) {
// we have a discriminator column
if (hasSubclasses || !discriminatorColumn.isImplicit()) {
bindDiscriminatorColumnToRootPersistentClass((RootClass) persistentClass, discriminatorColumn, entityBinder.getSecondaryTables(), propertyHolder, context);
//bind it again since the type might have changed
entityBinder.bindDiscriminatorValue();
}
}
}
} else if (InheritanceType.SINGLE_TABLE.equals(inheritanceState.getType())) {
if (isInheritanceRoot) {
if (hasSubclasses || !discriminatorColumn.isImplicit()) {
bindDiscriminatorColumnToRootPersistentClass((RootClass) persistentClass, discriminatorColumn, entityBinder.getSecondaryTables(), propertyHolder, context);
//bind it again since the type might have changed
entityBinder.bindDiscriminatorValue();
}
}
}
if (onDeleteAnn != null && !onDeleteAppropriate) {
LOG.invalidOnDeleteAnnotation(propertyHolder.getEntityName());
}
// try to find class level generators
HashMap<String, IdentifierGeneratorDefinition> classGenerators = buildLocalGenerators(clazzToProcess, context);
// check properties
final InheritanceState.ElementsToProcess elementsToProcess = inheritanceState.getElementsToProcess();
inheritanceState.postProcess(persistentClass, entityBinder);
final boolean subclassAndSingleTableStrategy = inheritanceState.getType() == InheritanceType.SINGLE_TABLE && inheritanceState.hasParents();
Set<String> idPropertiesIfIdClass = new HashSet<String>();
boolean isIdClass = mapAsIdClass(inheritanceStatePerClass, inheritanceState, persistentClass, entityBinder, propertyHolder, elementsToProcess, idPropertiesIfIdClass, context);
if (!isIdClass) {
entityBinder.setWrapIdsInEmbeddedComponents(elementsToProcess.getIdPropertyCount() > 1);
}
processIdPropertiesIfNotAlready(inheritanceStatePerClass, context, persistentClass, entityBinder, propertyHolder, classGenerators, elementsToProcess, subclassAndSingleTableStrategy, idPropertiesIfIdClass);
if (!inheritanceState.hasParents()) {
final RootClass rootClass = (RootClass) persistentClass;
context.getMetadataCollector().addSecondPass(new CreateKeySecondPass(rootClass));
} else {
superEntity.addSubclass((Subclass) persistentClass);
}
context.getMetadataCollector().addEntityBinding(persistentClass);
//Process secondary tables and complementary definitions (ie o.h.a.Table)
context.getMetadataCollector().addSecondPass(new SecondaryTableSecondPass(entityBinder, propertyHolder, clazzToProcess));
//add process complementary Table definition (index & all)
entityBinder.processComplementaryTableDefinitions(clazzToProcess.getAnnotation(org.hibernate.annotations.Table.class));
entityBinder.processComplementaryTableDefinitions(clazzToProcess.getAnnotation(org.hibernate.annotations.Tables.class));
entityBinder.processComplementaryTableDefinitions(tabAnn);
}
Aggregations