javax.persistence.Table Java Examples

The following examples show how to use javax.persistence.Table. 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 File: EntityInfo.java    From jeesuite-libs with 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 #2
Source File: EntityHelper.java    From jeesuite-libs with 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 #3
Source File: EntityUtils.java    From mybatis-boost with 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 #4
Source File: EntityUtils.java    From jpa-unit with 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 #5
Source File: EntityUtilsTest.java    From jpa-unit with 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 #6
Source File: BaseProvider.java    From ace with 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 #7
Source File: EntityHelper.java    From mybatis-dynamic-query with 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 #8
Source File: EntityHelper.java    From azeroth with 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 File: EntityRefelectUtils.java    From FastSQL with 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 #10
Source File: EntityInfo.java    From azeroth with 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 #11
Source File: AbstractModelService.java    From elexis-3-core with Eclipse Public License 1.0 5 votes vote down vote up
private <T> String getTableName(EntityManager em, Class<T> entityClass){
	/*
	 * Check if the specified class is present in the metamodel.
	 * Throws IllegalArgumentException if not.
	 */
	Metamodel meta = em.getMetamodel();
	EntityType<T> entityType = meta.entity(entityClass);
	
	//Check whether @Table annotation is present on the class.
	Table t = entityClass.getAnnotation(Table.class);
	
	String tableName = (t == null) ? entityType.getName().toUpperCase() : t.name();
	return tableName;
}
 
Example #12
Source File: ModelSqlUtils.java    From jdbctemplatetool with Apache License 2.0 5 votes vote down vote up
/**
 * 从po类获取表名
 * @return
 */
private static <T> String getTableName(Class<T> clazz) {
	
	Table tableAnno = clazz.getAnnotation(Table.class);
	if(tableAnno != null){
		if(tableAnno.catalog() != null){
			return tableAnno.catalog() + "." + tableAnno.name();
		}
		return tableAnno.name();
	}
	//if Table annotation is null
	String className = clazz.getName();
	return IdUtils.toUnderscore(className.substring(className.lastIndexOf(".")+1));
}
 
Example #13
Source File: ElectricPowerQualitySummaryPersistenceTests.java    From OpenESPI-Common-java with Apache License 2.0 5 votes vote down vote up
@Test
public void persistence() {
	TestUtils.assertAnnotationPresent(ElectricPowerQualitySummary.class,
			Entity.class);
	TestUtils.assertAnnotationPresent(ElectricPowerQualitySummary.class,
			Table.class);
}
 
Example #14
Source File: AbstractDatabaseTest.java    From jadira with Apache License 2.0 5 votes vote down vote up
protected void verifyDatabaseTable() {
    EntityManager manager = factory.createEntityManager();
    verifyDatabaseTable(manager, tableType.getAnnotation(Table.class).name());

    manager.clear();

    manager.close();
}
 
Example #15
Source File: BaseDao.java    From ranger with Apache License 2.0 5 votes vote down vote up
public void setIdentityInsert(boolean identityInsert) {
	if (RangerBizUtil.getDBFlavor() != AppConstants.DB_FLAVOR_SQLSERVER) {
		logger.debug("Ignoring BaseDao.setIdentityInsert(). This should be executed if DB flavor is sqlserver.");
		return;
	}

	EntityManager entityMgr = getEntityManager();

	String identityInsertStr;
	if (identityInsert) {
		identityInsertStr = "ON";
	} else {
		identityInsertStr = "OFF";
	}

	Table table = tClass.getAnnotation(Table.class);

	if(table == null) {
		throw new NullPointerException("Required annotation `Table` not found");
	}

	String tableName = table.name();

	try {
		entityMgr.unwrap(Connection.class).createStatement().execute("SET IDENTITY_INSERT " + tableName + " " + identityInsertStr);
	} catch (SQLException e) {
		logger.error("Error while settion identity_insert " + identityInsertStr, e);
	}
}
 
Example #16
Source File: SqlGenerateUtil.java    From jeecg with Apache License 2.0 5 votes vote down vote up
/**
 * 获取OBJ对应的table名
 * @param searchObj
 * @return
 */
public static String generateTable(Object searchObj){
	Table table = searchObj.getClass().getAnnotation(Table.class);
	if(StringUtil.isEmpty(table.name())){
		return searchObj.getClass().getSimpleName();
	}else{
		return table.name();
	}
}
 
Example #17
Source File: SavedSearch.java    From find with MIT License 5 votes vote down vote up
@SuppressWarnings("unused")
@Access(AccessType.PROPERTY)
@Column(name = Table.Column.DATE_RANGE_TYPE)
@JsonIgnore
public Integer getDateRangeInt() {
    return dateRange == null ? null : dateRange.getId();
}
 
Example #18
Source File: Mapper.java    From warpdb with Apache License 2.0 5 votes vote down vote up
String getTableName(Class<?> clazz) {
	Table table = clazz.getAnnotation(Table.class);
	if (table != null && !table.name().isEmpty()) {
		return table.name();
	}
	return NameUtils.toCamelCaseName(clazz.getSimpleName());
}
 
Example #19
Source File: BaseDao.java    From ranger with Apache License 2.0 5 votes vote down vote up
public void updateUserIDReference(String paramName,long oldID) {
	Table table = tClass.getAnnotation(Table.class);
	if(table != null) {
		String tableName = table.name();
		String query = "update " + tableName + " set " + paramName+"=null"
				+ " where " +paramName+"=" + oldID;
		int count=getEntityManager().createNativeQuery(query).executeUpdate();
		if(count>0){
			logger.warn(count + " records updated in table '" + tableName + "' with: set " + paramName + "=null where " + paramName + "=" + oldID);
		}
	}else{
		logger.warn("Required annotation `Table` not found");
	}
}
 
Example #20
Source File: SqlGenerateUtil.java    From bamboobsc with Apache License 2.0 5 votes vote down vote up
private static String getTableName(Object entityObject) throws Exception {
	String tableName="";
	Annotation annotations[]=entityObject.getClass().getAnnotations();
	for (Annotation annotation : annotations) {
		if (annotation instanceof Table) {
			tableName=StringUtils.defaultString(((Table)annotation).name());
		}
	}
	return tableName;
}
 
Example #21
Source File: BaseDaoMysqlImpl.java    From Crawer with MIT License 5 votes vote down vote up
protected BaseDaoMysqlImpl(Class<T> persistentClass) {
	this.persistentClass = persistentClass;
	Table table = AnnotationUtils.findAnnotation(persistentClass,
			Table.class);
	if (table == null) {
		throw new RuntimeException(persistentClass + "没有定义@table");
	}
	this.tableName = table.name();
	BeanInfo beanInfo = null;
	try {
		beanInfo = Introspector.getBeanInfo(persistentClass);
	} catch (IntrospectionException e) {
		log.error(e.getMessage(), e);
	}
	PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
	for (PropertyDescriptor pd : pds) {
		Id id = AnnotationUtils
				.findAnnotation(pd.getReadMethod(), Id.class);
		if (pk.equals("") && id != null) {
			pk = pd.getName();
			GeneratedValue gv = AnnotationUtils.findAnnotation(
					pd.getReadMethod(), GeneratedValue.class);
			if (gv == null) {
				strategy = GenerationType.IDENTITY;
			} else {
				strategy = gv.strategy();
			}
		}
		Transient transient_ = AnnotationUtils.findAnnotation(
				pd.getReadMethod(), Transient.class);
		if (transient_ != null) {
			transientPropertys.add(pd.getName());
		}
	}
	if ("".equals(this.getPk())) {
		throw new RuntimeException(persistentClass + "类型中没有在get方法上定义@Id");
	}
}
 
Example #22
Source File: JavaxPersistenceImpl.java    From ormlite-core with ISC License 5 votes vote down vote up
@Override
public String getEntityName(Class<?> clazz) {
	Entity entityAnnotation = clazz.getAnnotation(Entity.class);
	Table tableAnnotation = clazz.getAnnotation(Table.class);

	if (entityAnnotation != null && stringNotEmpty(entityAnnotation.name())) {
		return entityAnnotation.name();
	}
	if (tableAnnotation != null && stringNotEmpty(tableAnnotation.name())) {
		return tableAnnotation.name();
	}
	return null;
}
 
Example #23
Source File: DatabaseIntegrationTest.java    From realworld-api-quarkus with 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 #24
Source File: UserDaoJpa.java    From ankush with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public String getUserPassword(String username) {
	SimpleJdbcTemplate jdbcTemplate = new SimpleJdbcTemplate(dataSource);
	Table table = AnnotationUtils.findAnnotation(User.class, Table.class);
	return jdbcTemplate.queryForObject(
			"select password from " + table.name() + " where username=?",
			String.class, username);
}
 
Example #25
Source File: Mapper.java    From warpdb with Apache License 2.0 5 votes vote down vote up
String getUniqueKey() {
	Table table = this.entityClass.getAnnotation(Table.class);
	if (table != null) {
		return Arrays.stream(table.uniqueConstraints()).map((c) -> {
			String name = c.name().isEmpty() ? "UNI_" + String.join("_", c.columnNames()) : c.name();
			return "  CONSTRAINT " + name + " UNIQUE (" + String.join(", ", c.columnNames()) + "),\n";
		}).reduce("", (acc, s) -> {
			return acc + s;
		});
	}
	return "";
}
 
Example #26
Source File: IdGeneratorConfig.java    From dal with Apache License 2.0 5 votes vote down vote up
private String parseEntityTableName(Class<?> entityClazz) {
    Table table = entityClazz.getAnnotation(Table.class);
    if (table != null && !table.name().trim().isEmpty()) {
        return table.name().trim();
    }
    Entity entity = entityClazz.getAnnotation(Entity.class);
    if (entity != null && !entity.name().trim().isEmpty()) {
        return entity.name().trim();
    }
    return entityClazz.getSimpleName();
}
 
Example #27
Source File: EntityManager.java    From dal with 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;
	}
}
 
Example #28
Source File: EntityUtilsTest.java    From jpa-unit with 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 #29
Source File: EntityUtilsTest.java    From jpa-unit with 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 #30
Source File: EntityUtilsTest.java    From jpa-unit with 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));
}