Java Code Examples for javax.persistence.Table

The following examples show how to use javax.persistence.Table. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: mybatis-boost   Source File: EntityUtils.java    License: MIT License 6 votes vote down vote up
public static String getTableName(Class<?> type, NameAdaptor converter) {
    return tableNameCache.computeIfAbsent(type, k -> {
        if (type.isAnnotationPresent(Table.class)) {
            Table table = type.getAnnotation(Table.class);
            String catalog = table.catalog();
            if (StringUtils.isEmpty(catalog)) {
                catalog = table.schema();
            }
            if (StringUtils.isEmpty(catalog)) {
                return table.name();
            } else {
                return String.format("`%s`.`%s`", catalog, table.name());
            }
        } else {
            return converter.adapt(type.getSimpleName());
        }
    });
}
 
Example 2
Source Project: ace   Source File: BaseProvider.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * queryByPrimaryKey
 *
 * @param obj 实体bean
 * @return sql
 */
public String queryByPrimaryKey(Object obj) {
    Table table = getTable(obj);
    String key = "queryByPrimaryKey_" + table.getClass();
    String sql = sqlMap.get(key);
    if (sql == null) {
        StringBuilder stringBuilder = new StringBuilder("select ");
        StringBuilder columnStr = new StringBuilder();
        Map<String, String> columnMap = columnMap(obj.getClass());
        for (Map.Entry<String, String> entry : columnMap.entrySet()) {
            columnStr.append(entry.getKey());
            columnStr.append(" as ");
            columnStr.append(entry.getValue());
            columnStr.append(" ,");
        }
        columnStr.deleteCharAt(columnStr.lastIndexOf(","));
        stringBuilder.append(columnStr.toString());
        stringBuilder.append(" from ");
        stringBuilder.append(table.name());
        stringBuilder.append(buildWhereByPrimaryKey(obj.getClass()));
        sql = stringBuilder.toString();
        sqlMap.put(key, sql);

    }
    return sql;
}
 
Example 3
Source Project: FastSQL   Source File: EntityRefelectUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 获取指定实体类对应的表名
 *
 * @param entityClass 实体类的类型令牌
 * @return 若指定的类中含有{@code javax.persistence.Table}注解,则返回注解的name字段的值
 */
public static String getTableNameFromEntityClass(Class<?> entityClass) {
    //获取类名
    final String className = entityClass.getSimpleName();
    //通过将类名由驼峰转为蛇形获取表名
    String tableName = StringExtUtils.camelToUnderline(className);
    //获取实体类中的Table注解实例
    final Table table = entityClass.getAnnotation(Table.class);
    //判断实例是否非空
    if (table != null) {
        if (!StringUtils.isEmpty(table.name())) {
            tableName = table.name();
        }
    }
    //返回表名
    return tableName;
}
 
Example 4
Source Project: azeroth   Source File: EntityInfo.java    License: Apache License 2.0 6 votes vote down vote up
public EntityInfo(String mapperClassName, String entityClassName, String tableName) {
    this.tableName = tableName;
    try {
        if (StringUtils.isNotBlank(entityClassName)) { entityClass = Class.forName(entityClassName); }
        if (StringUtils.isBlank(this.tableName)) { this.tableName = entityClass.getAnnotation(Table.class).name(); }
        mapperClass = Class.forName(mapperClassName);
    } catch (Exception e) {
        try {
            //根据mapper接口解析entity Class
            Type[] types = mapperClass.getGenericInterfaces();
            Type[] tempTypes = ((ParameterizedType) types[0]).getActualTypeArguments();
            Class<?> clazz = (Class<?>) tempTypes[0];
            if (clazz != null) {
                entityClass = clazz;
            }
        } catch (Exception e1) {}
    }
}
 
Example 5
Source Project: azeroth   Source File: EntityHelper.java    License: Apache License 2.0 6 votes vote down vote up
private static TableMapper getTableMapper(Class<?> entityClass) {
    // 表名
    TableMapper tableMapper = new TableMapper();
    String tableName = null;
    if (entityClass.isAnnotationPresent(Table.class)) {
        Table table = entityClass.getAnnotation(Table.class);
        if (!table.name().equals("")) {
            tableName = table.name();
        } else {
            tableName = camelhumpToUnderline(entityClass.getSimpleName());
        }
    }

    if (tableName == null || tableName.equals("")) {
        throw new RuntimeException("实体" + entityClass.getName() + "不存在'Table'注解");
    }

    tableMapper.setName(tableName);
    return tableMapper;
}
 
Example 6
Source Project: mybatis-dynamic-query   Source File: EntityHelper.java    License: Apache License 2.0 6 votes vote down vote up
static String getTableName(final Class<?> tableClass) {
    if (tableClass == null) {
        throw new NullPointerException("tableClass");
    }

    if (tableClass.isAnnotationPresent(Table.class)) {
        Table table = tableClass.getAnnotation(Table.class);
        String dbTableName = table.name();
        if (StringUtils.isNotBlank(dbTableName)) {
            return dbTableName;
        }
    }

    String useTableName = tableClass.getSimpleName();
    return camelCaseToUnderscore(useTableName);
}
 
Example 7
Source Project: jeesuite-libs   Source File: EntityInfo.java    License: Apache License 2.0 6 votes vote down vote up
public EntityInfo(String mapperClassName, String entityClassName, String tableName) {
	this.tableName = tableName;
	try {
		if(StringUtils.isNotBlank(entityClassName))entityClass = Class.forName(entityClassName);
		if(StringUtils.isBlank(this.tableName))this.tableName = entityClass.getAnnotation(Table.class).name();
		mapperClass = Class.forName(mapperClassName);
	} catch (Exception e) {
		try {					
			//根据mapper接口解析entity Class
			Type[] types = mapperClass.getGenericInterfaces();  
			Type[] tempTypes = ((ParameterizedType) types[0]).getActualTypeArguments();  
			Class<?> clazz = (Class<?>) tempTypes[0];
			if(clazz != null){
				entityClass = clazz;
			}
		} catch (Exception e1) {}
	}
}
 
Example 8
Source Project: jeesuite-libs   Source File: EntityHelper.java    License: Apache License 2.0 6 votes vote down vote up
private static TableMapper getTableMapper(Class<?> entityClass) {
    // 表名
    TableMapper tableMapper = new TableMapper();
    String tableName = null;
    if (entityClass.isAnnotationPresent(Table.class)) {
        Table table = entityClass.getAnnotation(Table.class);
        if (!table.name().equals("")) {
            tableName = table.name();
        } else {
            tableName = camelhumpToUnderline(entityClass.getSimpleName());
        }
    }

    if (tableName == null || tableName.equals("")) {
        throw new RuntimeException("实体" + entityClass.getName() + "不存在'Table'注解");
    }

    tableMapper.setName(tableName);
    return tableMapper;
}
 
Example 9
Source Project: jpa-unit   Source File: EntityUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static Class<?> getEntityClassFromNodeLabels(final List<String> labels, final List<Class<?>> classes)
        throws NoSuchClassException {
    for (final String label : labels) {
        final Optional<Class<?>> classHit = classes.stream().filter(c -> {
            // try to find the class based on its name
            if (c.getName().endsWith(label)) {
                return true;
            } else {
                // try to find the class based on the @Table(name) settings
                final Table annotation = c.getAnnotation(Table.class);
                return annotation != null && annotation.name().equals(label);
            }
        }).findFirst();

        if (classHit.isPresent()) {
            return classHit.get();
        }
    }

    throw new NoSuchClassException("could not find class for a node with " + labels + " labels.");
}
 
Example 10
Source Project: jpa-unit   Source File: EntityUtilsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGetEntityClassFromNodeLabelsHavingTheLabelDeclaredByTheTableAnnotationWithoutInheritance() throws Exception {
    final String simpleClassName = "EntityClass";
    final String nodeLabel = "ENTITY_CLASS";

    final JPackage jp = jCodeModel.rootPackage();
    final JDefinedClass jClass = jp._class(JMod.PUBLIC, simpleClassName);
    jClass.annotate(Entity.class);
    jClass.annotate(Table.class).param("name", nodeLabel);

    buildModel(testFolder.getRoot(), jCodeModel);

    compileModel(testFolder.getRoot());

    final Class<?> entityClass = loadClass(testFolder.getRoot(), jClass.name());

    final Class<?> clazz = EntityUtils.getEntityClassFromNodeLabels(Arrays.asList(nodeLabel), Arrays.asList(entityClass));

    assertThat(clazz, equalTo(entityClass));
}
 
Example 11
Source Project: realworld-api-quarkus   Source File: DatabaseIntegrationTest.java    License: MIT License 5 votes vote down vote up
private static void configEntityClasses(Configuration configuration, String packageToScan) {
  Reflections reflections = new Reflections(packageToScan);
  reflections
      .getTypesAnnotatedWith(Entity.class)
      .forEach(
          entity -> {
            String tableName = entity.getAnnotation(Table.class).name();
            entities.add(tableName);
            configuration.addAnnotatedClass(entity);
          });
}
 
Example 12
Source Project: anyline   Source File: BeanUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static String checkTable(Class<?> clazz){ 
	String result = null; 
	try{ 
		Annotation annotation = clazz.getAnnotation(Table.class);					//提取Table注解 
		Method method = annotation.annotationType().getMethod("name");				//引用name方法 
		result = (String)method.invoke(annotation);									//执行name方法返回结果 
	}catch(Exception e){ 
		e.printStackTrace(); 
	} 
	return result; 
}
 
Example 13
Source Project: base-admin   Source File: SqlUtil.java    License: MIT License 5 votes vote down vote up
/**
 *
 * @param entity 自动拼接实体对象字段
 * @param ignoreProperties 动态参数  忽略拼接的字段
 * @return sql
 */
public static StringBuilder appendFields(Object entity, String... ignoreProperties) {
    StringBuilder sql = new StringBuilder();
    List<String> ignoreList = Arrays.asList(ignoreProperties);
    try {
        sql.append("select ");

        for (Field field : entity.getClass().getDeclaredFields()) {
            //获取授权
            field.setAccessible(true);
            String fieldName = field.getName();//属性名称
            Object fieldValue = field.get(entity);//属性的值
            //非临时字段、非忽略字段
            if (!field.isAnnotationPresent(Transient.class) && !ignoreList.contains(fieldName)) {
                //拼接查询字段  驼峰属性转下划线
                sql.append(new PropertyNamingStrategy.SnakeCaseStrategy().translate(fieldName).toLowerCase()).append(" ").append(",");
            }
        }
        //处理逗号(删除最后一个字符)
        sql.deleteCharAt(sql.length() - 1);

        String tableName = entity.getClass().getAnnotation(Table.class).name();
        sql.append("from ").append(tableName).append(" where '1' = '1' ");
    } catch (IllegalAccessException e) {
        //输出到日志文件中
        log.error(ErrorUtil.errorInfoToString(e));
    }
    return sql;
}
 
Example 14
Source Project: jstarcraft-core   Source File: HibernateMetadata.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 构造方法
 * 
 * @param metadata
 */
HibernateMetadata(Class<?> clazz) {
    ormClass = clazz;
    ormName = clazz.getName();
    ReflectionUtility.doWithFields(ormClass, (field) -> {
        if (Modifier.isStatic(field.getModifiers()) || Modifier.isTransient(field.getModifiers())) {
            return;
        }
        if (field.isAnnotationPresent(Version.class)) {
            versionName = field.getName();
            return;
        }
        Class<?> type = ClassUtility.primitiveToWrapper(field.getType());
        if (String.class == type) {
            fields.put(field.getName(), type);
        } else if (type.isEnum()) {
            fields.put(field.getName(), type);
        } else if (Collection.class.isAssignableFrom(type) || type.isArray()) {
            fields.put(field.getName(), List.class);
        } else if (Date.class.isAssignableFrom(type)) {
            fields.put(field.getName(), Date.class);
        } else {
            fields.put(field.getName(), Map.class);
        }
        if (field.isAnnotationPresent(Id.class) || field.isAnnotationPresent(EmbeddedId.class)) {
            primaryName = field.getName();
            primaryClass = type;
        }
    });
    Table table = clazz.getAnnotation(Table.class);
    if (table != null) {
        for (Index index : table.indexes()) {
            indexNames.add(index.columnList());
        }
    }
}
 
Example 15
Source Project: ace   Source File: BaseProvider.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * insert
 *
 * @param obj 实体bean
 * @return sql
 */
public String insert(Object obj) {
    Table table = getTable(obj);
    String key = "insert_" + table.getClass();
    String sql = sqlMap.get(key);
    if (sql == null) {
        StringBuilder stringBuilder = new StringBuilder("insert into ");
        stringBuilder.append(table.name());
        stringBuilder.append("(");
        StringBuilder values = new StringBuilder("(");
        Map<String, String> columnMap = columnMap(obj.getClass());
        for (Map.Entry<String, String> entry : columnMap.entrySet()) {
            stringBuilder.append(entry.getKey());
            stringBuilder.append(",");
            values.append("#{");
            values.append(entry.getValue());
            values.append("},");
        }
        stringBuilder.deleteCharAt(stringBuilder.lastIndexOf(","));
        values.deleteCharAt(values.lastIndexOf(","));
        stringBuilder.append(" ) values ");
        values.append(" )");
        stringBuilder.append(values.toString());
        sqlMap.put(key, sql);

    }
    return sql;
}
 
Example 16
Source Project: ace   Source File: BaseProvider.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * update
 *
 * @param obj 实体bean
 * @return sql
 */
public String update(Object obj) {
    Table table = getTable(obj);
    String key = "update_" + table.getClass();
    String sql = sqlMap.get(key);
    if (sql == null) {
        StringBuilder stringBuilder = new StringBuilder(" update ");
        stringBuilder.append(table.name());
        stringBuilder.append(" set ");
        Map<String, String> columnMap = columnMap(obj.getClass());
        StringBuilder columnStr = new StringBuilder();
        for (Map.Entry<String, String> entry : columnMap.entrySet()) {
            columnStr.append(entry.getKey());
            columnStr.append(" = #{");
            columnStr.append(entry.getValue());
            columnStr.append(" } ,");

        }
        columnStr.deleteCharAt(columnStr.lastIndexOf(","));
        stringBuilder.append(columnStr.toString());
        stringBuilder.append(buildWhereByPrimaryKey(obj.getClass()));
        sql = stringBuilder.toString();
        sqlMap.put(key, sql);
    }

    return sql;


}
 
Example 17
Source Project: ace   Source File: BaseProvider.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * delete
 *
 * @param obj 实体bean
 * @return sql
 */
public String delete(Object obj) {
    Table table = getTable(obj);
    String key = "delete_" + table.getClass();
    String sql = sqlMap.get(key);
    if (sql == null) {
        StringBuilder stringBuilder = new StringBuilder("delete from  ");
        stringBuilder.append(table.name());
        stringBuilder.append(buildWhereByPrimaryKey(obj.getClass()));
        sql = stringBuilder.toString();
        sqlMap.put(key, sql);

    }
    return sql;
}
 
Example 18
Source Project: ace   Source File: BaseProvider.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 获取table名称
 *
 * @param obj 实体bean
 * @return table
 */
private Table getTable(Object obj) {
    Table table = obj.getClass().getAnnotation(Table.class);
    if (table == null || "".equals(table.name().trim())) {
        throw new RuntimeException("the class  must  has @table.name() ");
    }
    return table;
}
 
Example 19
Source Project: o2oa   Source File: CheckCore.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
public static void checkTableNameUniqueConstraintName(List<Class<?>> classes) throws Exception {
	for (Class<?> cls : classes) {
		Table table = cls.getAnnotation(Table.class);
		String name = Objects.toString(FieldUtils.readStaticField(cls, "TABLE", true));
		if (!StringUtils.equals(table.name(), name)) {
			System.out.println("table name not match:" + cls);
		}
		for (UniqueConstraint u : table.uniqueConstraints()) {
			if (!StringUtils.startsWith(u.name(), table.name())) {
				System.err.println(
						String.format("checkTableNameUniqueConstraintName error: class: %s.", cls.getName()));
			}
		}
	}
}
 
Example 20
Source Project: financisto   Source File: EntityManager.java    License: GNU General Public License v2.0 5 votes vote down vote up
private static EntityDefinition parseDefinition(Class<?> clazz) {
    if (!clazz.isAnnotationPresent(Entity.class)) {
        throw new IllegalArgumentException("Class " + clazz + " is not an @Entity");
    }
    EntityDefinition.Builder edb = new EntityDefinition.Builder(clazz);
    try {
        Constructor<?> constructor = clazz.getConstructor();
        edb.withConstructor(constructor);
    } catch (Exception e) {
        throw new IllegalArgumentException("Entity must have an empty constructor");
    }
    if (clazz.isAnnotationPresent(Table.class)) {
        Table tableAnnotation = clazz.getAnnotation(Table.class);
        edb.withTable(tableAnnotation.name());
    }
    Field[] fields = clazz.getFields();
    if (fields != null) {
        int index = 0;
        for (Field f : fields) {
            if ((f.getModifiers() & Modifier.STATIC) == 0) {
                if (f.isAnnotationPresent(Id.class)) {
                    edb.withIdField(parseField(f));
                } else {
                    if (!f.isAnnotationPresent(Transient.class)) {
                        if (f.isAnnotationPresent(JoinColumn.class)) {
                            JoinColumn c = f.getAnnotation(JoinColumn.class);
                            edb.withField(FieldInfo.entity(index++, f, c.name(), c.required()));
                        } else {
                            edb.withField(parseField(f));
                        }
                    }
                }
            }
        }
    }
    return edb.create();
}
 
Example 21
Source Project: mybatis.flying   Source File: SqlBuilder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * To determine whether clazz meets the criteria, whether there is a
 * TableMapperAnnotation type annotation. If there is one return true, else
 * return false
 * 
 * @param clazz
 * @return
 */
private static boolean interview(Class<?> clazz) {
	Annotation[] classAnnotations = clazz.getDeclaredAnnotations();
	if (classAnnotations.length > 0) {
		for (Annotation an : classAnnotations) {
			if (an instanceof TableMapperAnnotation || an instanceof Table) {
				return true;
			}
		}
	}
	return false;
}
 
Example 22
Source Project: mybatis-jpa   Source File: PersistentUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static String getTableName(Class<?> clazz, NamingStrategy namingStrategy) {
  if (clazz.isAnnotationPresent(Table.class)) {
    Table table = clazz.getAnnotation(Table.class);
    if (!"".equals(table.name().trim())) {
      return table.name();
    }
  }
  String tableName = clazz.getSimpleName();

  return namingStrategy.translate(tableName);
}
 
Example 23
Source Project: wangmarket   Source File: SqlDAO.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 从JPA的实体类中,获取数据库表的名字
 * @param c 实体类,如 User.class
 * @return 此实体类的数据表的原名
 */
public static String getDatabaseTableName(Class c){
	Table table = (Table) c.getAnnotation(javax.persistence.Table.class);
	String tableName = null;
	if(table != null && table.name() != null && table.name().length() > 0){
		tableName = table.name();
	}else{
		tableName = StringUtil.firstCharToLowerCase(c.getSimpleName());
	}
	return tableName;
}
 
Example 24
Source Project: tephra   Source File: CreateImpl.java    License: MIT License 5 votes vote down vote up
@Override
public void create(String dataSource, ModelTable modelTable, String tableName) {
    String[] array = read(modelTable.getModelClass());
    if (array == null)
        return;

    String name = modelTable.getModelClass().getAnnotation(Table.class).name();
    for (String string : array)
        executer.execute(dataSource, string.replaceFirst(name, tableName), true);
}
 
Example 25
private static String getUniqueColumns(Class<?> clazz, String name) {
    return Optional.of(clazz)
        .map(c -> c.getAnnotation(Table.class))
        .map(Table::uniqueConstraints)
        .map(Stream::of)
        .flatMap(s -> s
            .filter(uc -> uc.name().equals(name))
            .findAny()
            .map(UniqueConstraint::columnNames))
        .map(Stream::of)
        .map(s -> s.collect(Collectors.joining(", ")))
        .get();
}
 
Example 26
Source Project: gd-generator   Source File: ClassHelper.java    License: MIT License 5 votes vote down vote up
public static String resolveTableName(Class<?> entityClass) {
    Table table = entityClass.getDeclaredAnnotation(Table.class);
    if (table == null) {
        throw new IllegalArgumentException("@Table注解缺失");
    }
    if (StringUtils.isNotBlank(table.name())) {
        return table.name();
    } else {
        return StringUtils.camelToUnderline(entityClass.getSimpleName());
    }
}
 
Example 27
Source Project: jpa-unit   Source File: EntityUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGetEntityClassFromNodeLabelsHavingTheLabelDeclaredByTheTableAnnotationWithSingleTableInheritance() throws Exception {
    final String simpleClassNameBase = "EntityClass";
    final String simpleClassNameA = "SubEntityClassA";
    final String simpleClassNameB = "SubEntityClassB";

    final String nodeLabel = "ENTITY_CLASS";

    final JPackage jp = jCodeModel.rootPackage();
    final JDefinedClass jBaseClass = jp._class(JMod.PUBLIC, simpleClassNameBase);
    jBaseClass.annotate(Entity.class);
    jBaseClass.annotate(Table.class).param("name", nodeLabel);
    jBaseClass.annotate(Inheritance.class).param("strategy", InheritanceType.SINGLE_TABLE);
    jBaseClass.annotate(DiscriminatorColumn.class).param("name", "TYPE");

    final JDefinedClass jSubclassA = jp._class(JMod.PUBLIC, simpleClassNameA)._extends(jBaseClass);
    jSubclassA.annotate(Entity.class);
    jSubclassA.annotate(DiscriminatorValue.class).param("value", "A");

    final JDefinedClass jSubclassB = jp._class(JMod.PUBLIC, simpleClassNameB)._extends(jBaseClass);
    jSubclassB.annotate(Entity.class);
    jSubclassB.annotate(DiscriminatorValue.class).param("value", "B");

    buildModel(testFolder.getRoot(), jCodeModel);

    compileModel(testFolder.getRoot());

    final Class<?> baseClass = loadClass(testFolder.getRoot(), jBaseClass.name());
    final Class<?> subClassA = loadClass(testFolder.getRoot(), jSubclassA.name());
    final Class<?> subClassB = loadClass(testFolder.getRoot(), jSubclassB.name());

    final Class<?> clazz = EntityUtils.getEntityClassFromNodeLabels(Arrays.asList(nodeLabel),
            Arrays.asList(baseClass, subClassA, subClassB));

    assertThat(clazz, equalTo(baseClass));
}
 
Example 28
Source Project: jpa-unit   Source File: EntityUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGetEntityClassFromNodeLabelsHavingTheLabelDeclaredByTheTableAnnotationWithTablePerClassInheritance() throws Exception {
    final String simpleClassNameBase = "EntityClass";
    final String simpleClassNameA = "SubEntityClassA";
    final String simpleClassNameB = "SubEntityClassB";

    final String nodeLabelBase = "ENTITY_CLASS";
    final String nodeLabelA = "ENTITY_CLASS_A";
    final String nodeLabelB = "ENTITY_CLASS_B";

    final JPackage jp = jCodeModel.rootPackage();
    final JDefinedClass jBaseClass = jp._class(JMod.PUBLIC, simpleClassNameBase);
    jBaseClass.annotate(Entity.class);
    jBaseClass.annotate(Table.class).param("name", nodeLabelBase);
    jBaseClass.annotate(Inheritance.class).param("strategy", InheritanceType.TABLE_PER_CLASS);

    final JDefinedClass jSubclassA = jp._class(JMod.PUBLIC, simpleClassNameA)._extends(jBaseClass);
    jSubclassA.annotate(Entity.class);
    jSubclassA.annotate(Table.class).param("name", nodeLabelA);

    final JDefinedClass jSubclassB = jp._class(JMod.PUBLIC, simpleClassNameB)._extends(jBaseClass);
    jSubclassB.annotate(Entity.class);
    jSubclassB.annotate(Table.class).param("name", nodeLabelB);

    buildModel(testFolder.getRoot(), jCodeModel);

    compileModel(testFolder.getRoot());

    final Class<?> baseClass = loadClass(testFolder.getRoot(), jBaseClass.name());
    final Class<?> subClassA = loadClass(testFolder.getRoot(), jSubclassA.name());
    final Class<?> subClassB = loadClass(testFolder.getRoot(), jSubclassB.name());

    final Class<?> clazz = EntityUtils.getEntityClassFromNodeLabels(Arrays.asList(nodeLabelA),
            Arrays.asList(baseClass, subClassA, subClassB));

    assertThat(clazz, equalTo(subClassA));
}
 
Example 29
Source Project: jpa-unit   Source File: EntityUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGetEntityClassFromNodeLabelsHavingTheLabelDeclaredByTheTableAnnotationWithJoinedInheritance() throws Exception {
    final String simpleClassNameBase = "EntityClass";
    final String simpleClassNameA = "SubEntityClassA";
    final String simpleClassNameB = "SubEntityClassB";

    final String nodeLabelBase = "ENTITY_CLASS";
    final String nodeLabelA = "ENTITY_CLASS_A";
    final String nodeLabelB = "ENTITY_CLASS_B";

    final JPackage jp = jCodeModel.rootPackage();
    final JDefinedClass jBaseClass = jp._class(JMod.PUBLIC, simpleClassNameBase);
    jBaseClass.annotate(Entity.class);
    jBaseClass.annotate(Table.class).param("name", nodeLabelBase);
    jBaseClass.annotate(Inheritance.class).param("strategy", InheritanceType.JOINED);

    final JDefinedClass jSubclassA = jp._class(JMod.PUBLIC, simpleClassNameA)._extends(jBaseClass);
    jSubclassA.annotate(Entity.class);
    jSubclassA.annotate(Table.class).param("name", nodeLabelA);

    final JDefinedClass jSubclassB = jp._class(JMod.PUBLIC, simpleClassNameB)._extends(jBaseClass);
    jSubclassB.annotate(Entity.class);
    jSubclassB.annotate(Table.class).param("name", nodeLabelB);

    buildModel(testFolder.getRoot(), jCodeModel);

    compileModel(testFolder.getRoot());

    final Class<?> baseClass = loadClass(testFolder.getRoot(), jBaseClass.name());
    final Class<?> subClassA = loadClass(testFolder.getRoot(), jSubclassA.name());
    final Class<?> subClassB = loadClass(testFolder.getRoot(), jSubclassB.name());

    final Class<?> clazz = EntityUtils.getEntityClassFromNodeLabels(Arrays.asList(nodeLabelA),
            Arrays.asList(baseClass, subClassA, subClassB));

    assertThat(clazz, equalTo(subClassA));
}
 
Example 30
Source Project: dal   Source File: EntityManager.java    License: Apache License 2.0 5 votes vote down vote up
private void processTableAnnotation(Class<?> clazz) {
	Table table = clazz.getAnnotation(Table.class);
	if (table == null)
		return;

	String name = table.name();
	if (name == null)
		return;

	if (tableName == null) {
		tableName = name;
	}
}