/** * 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; }
/** * 获取指定实体类对应的表名 * * @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) { //若非空,判断元数据name是否不为空字符串 if (!StringUtils.isEmpty(table.name())) { //若是,则使用name的值覆盖表名 tableName = table.name(); } } //返回表名 return tableName; }
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) {} } }
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; }
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); }
/** * Registers the given model and controller with a database persister, getting the bucket name * from the @Table annotation on the model. * * @param model * @param controller * @param stash * @return */ public ModelController registerDbModel(Class<? extends Model> model, Class<? extends ModelController> controller, Class<? extends Stash> stash, String bucket) { Table anno = model.getAnnotation(Table.class); if (anno == null) { throw new UsageException("A @Table annotation is required on the model " + model.getCanonicalName() + " in order to register it."); } bucket = or(bucket, anno.name()); String table = anno.name(); DataAccessRegistration registration = new DataAccessRegistration() .setDatabaseBacked(true) .setPersisterClass(DbPersister.class) .setBucket(bucket) .setTableName(table) .setControllerClass(controller) .setStashClass(stash) .setModelClass(model); return register(registration); }
@Test public void testDeleteUploadTable() throws Exception { TableData tableData = new TableData(); tableData.setTableName(RtEvent.class.getAnnotation(Table.class).name()); RowData value = new RowData(); ObjectList list = new ObjectList(); list.getObjects().add(0L); list.getObjects().add(0L); list.getObjects().add("gif"); value.getRows().add(list); tableData.setData(value); tableData.setForceCleanup(true); StringList stringList = new StringList(); stringList.getStrings().add("EVENT_NR"); stringList.getStrings().add("CLIENT_NR"); stringList.getStrings().add("FORMAT"); tableData.setColumns(stringList); UploadUtility.deleteTable(tableData, Long.MAX_VALUE, 0L); }
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) {} } }
/** * Returns the table name for a given entity type in the * {@link EntityManager}. * * @param entityClass * @return */ public <T> String getTableName(Class<T> entityClass) { /* * Check if the specified class is present in the metamodel. Throws * IllegalArgumentException if not. */ Metamodel meta = entityManager.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(); logger.debug("Table name found: {}", tableName); return tableName; }
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."); }
@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)); }
/** * 获取主键的值 * @param target Entity的class类型 * @return 如果该Entity没有@Id注解,则return null,如果有一个则返回{val},两个则返回{val1, val2} * 其中的val值可能为null,所以需要实时判断下 */ public static Object[] getPkValues(Object target) { Assert.notNull(target, "target param must not be null."); Assert.isInstanceOf(Entity.class, target); com.easycodebox.jdbc.Table table = Configuration.getTable(target.getClass()); if(table != null) { List<com.easycodebox.jdbc.PkColumn> pks = table.getPrimaryKeys(); if(pks != null && pks.size() > 0) { Object[] vals = new Object[pks.size()]; for(int i = 0; i < pks.size(); i++) { Object val; try { val = PropertyUtils.getSimpleProperty(target, pks.get(i).getName()); } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { throw new BaseException("Obtain object({0}) property({1}) error.", e, target, pks.get(i).getName()); } vals[i] = val; } return vals; } } return null; }
protected <T> void register(OObjectDatabaseTx db, OSchema schema, Class<T> aClass) { if (schema.getClass(aClass.getSimpleName()) == null) { db.getEntityManager().registerEntityClasses(aClass, true); OClass cls = db.getMetadata().getSchema().getClass(aClass); String indexName = aClass.getName() + ".unq"; Table t = aClass.getAnnotation(Table.class); if (t != null) { Set<String> fields = new HashSet<>(); for (UniqueConstraint uc : t.uniqueConstraints()) { fields.addAll(Lists.newArrayList(uc.columnNames())); } if (fields.size() > 0) { LOG.info("Registering unique constraint for fields: " + fields); for (String field : fields) cls.createIndex(indexName + "." + field, OClass.INDEX_TYPE.UNIQUE_HASH_INDEX, field); } } } else { db.getEntityManager().registerEntityClasses(aClass, true); } }
public static List<Ddl2Rest.Klass> map(final Table table) { Column[] _columns = table.getColumns(); final Function1<Column, Ddl2Rest.Klass> _function = (Column column) -> { Ddl2Rest.Klass _xblockexpression = null; { String _type = column.getType(); String type = Ddl2Rest.fieldType(_type); String columnName = column.getName(); String _name = column.getName(); String[] _split = _name.split("_"); final Function1<String, String> _function_1 = (String it) -> { return StringExtensions.toFirstUpper(it); }; List<String> _map = ListExtensions.<String, String>map(((List<String>)Conversions.doWrapArray(_split)), _function_1); String _join = IterableExtensions.join(_map); String name = StringExtensions.toFirstLower(_join); String comment = column.getDescription(); _xblockexpression = new Ddl2Rest.Klass(type, name, columnName, comment); } return _xblockexpression; }; return ListExtensions.<Column, Ddl2Rest.Klass>map(((List<Column>)Conversions.doWrapArray(_columns)), _function); }
@Test public void test() { doInJPA(entityManager -> { Table table = new Table(); table.id = 1L; table.from = "from"; table.number = 123; table.select = "*"; entityManager.persist(table); }); doInJPA(entityManager -> { List<Table> tables = entityManager.createQuery( "select t " + "from Table t " + "where t.from like 'from'", Table.class) .getResultList(); assertEquals(1, tables.size()); }); }
private String retrieveTable(final String className) { final int bI = className.lastIndexOf(".") + 1; String table = className.substring(bI); try { final Class<?> c = Class.forName(className); final Table tableAnnotation = c.getAnnotation(Table.class); table = tableAnnotation.name(); } catch (final Exception e) { LOG.error("Exception while retrieving 'table' annotation from the flexible element of type '" + className + "'.", e); } return table; }
protected void buildMap(Class<T> c) { if (c.isAnnotationPresent(Table.class)){ Table table = c.getAnnotation(Table.class); tablename = table.name(); } for (Field f : c.getDeclaredFields()) { if (f.isAnnotationPresent(Column.class)) { Column column = f.getAnnotation(Column.class); columnMap.put(f.getName(), column.name()); if (f.isAnnotationPresent(Id.class)) { primaryKeyField = f; f.setAccessible(true); primaryKeyName = column.name(); } } } }
private void initType(ModelType type) { Table table = type.getModelClass().getAnnotation(Table.class); String query = "select id, ref_id from " + table.name(); HashMap<String, Long> seq = new HashMap<>(); HashSet<String> inDb = new HashSet<>(); try { NativeSql.on(db).query(query, result -> { String refId = result.getString(2); seq.put(refId, result.getLong(1)); inDb.add(refId); return true; }); } catch (Exception e) { log.error("failed to initialize sequence map for " + type, e); } sequences[type.ordinal()] = seq; inDatabase[type.ordinal()] = inDb; }
/** * @return the number of entities in the table. */ public long getCount() { String entityName = entityClass.getSimpleName(); Table annotation = entityClass.getAnnotation(Table.class); String tableName; if (annotation != null) { tableName = annotation.name(); } else { tableName = entityName; } String qry = "select count(" + entityName + ") from " + tableName + " " + entityName; Query query = getEntityManager().createQuery(qry); Number countResult = (Number) query.getSingleResult(); return countResult.longValue(); }
public static void main( String[] args ) throws ClassNotFoundException { Class<? extends PersistableBusinessObjectBase> clazz = (Class<? extends PersistableBusinessObjectBase>) Class.forName(args[0]); StringBuffer sb = new StringBuffer( 1000 ); StringBuffer pk = new StringBuffer(); Table tableAnnotation = (Table)clazz.getAnnotation( Table.class ); sb.append( "CREATE TABLE " ).append( tableAnnotation.name().toLowerCase() ).append( " (\r\n" ); getClassFields( tableAnnotation.name().toLowerCase(), clazz, sb, pk, null ); pk.append( " )\r\n" ); sb.append( pk ); sb.append( ")\r\n" ); sb.append( "/\r\n" ); System.out.println( sb.toString() ); sb.setLength( 0 ); getReferences( clazz, sb ); System.out.println( sb.toString() ); }
/** * Given an entity, returns the table name for the entity. * @param entity the entity to lookup. * @return the name of the table for the entity. */ public static String getTableName(final Class<?> entity) { final Entity annotation = entity.getAnnotation(Entity.class); if(annotation == null) { throw new IllegalArgumentException(entity.getName() + " does not have the Entity annotation"); } final Table table = entity.getAnnotation(Table.class); // get the table's name from the annotation if(table != null && !table.name().isEmpty()) { return table.name(); } else { return entity.getSimpleName(); } }
public void initFromStore(String connectionBeanName, final Store store) throws JsonException { connectionBeanName_ = connectionBeanName; storeId_ = store.getId(); databaseId_ = store.getDatabase().getId(); instanceId_ = store.getDatabase().getInstance().getId(); documentId_ = ""; //$NON-NLS-1$ category_ = false; // Look for an @Table annotation to set the form Table tableAnnotation = getClass().getAnnotation(Table.class); if(tableAnnotation != null) { setValueImmediate("form", tableAnnotation.name()); //$NON-NLS-1$ } docJson_ = new JsonObject(); }
private void init() { Table table = model.getClass().getAnnotation(Table.class); if(table != null) { tableName = table.name(); } if(tableName == null || "".equals(tableName.trim())) { tableName = model.getClass().getSimpleName(); } }
/** * 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; }
/** * 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; }
/** * 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; }
/** * 获取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; }
/** * 获取pojo表名 * <p> * 下划线风格 * </p> * * @param clazz pojo类class对象 * @return tableName */ public static String getTableName(Class<?> clazz) { // 驼峰转下划线 String tableName = StringUtil.camelToUnderline(clazz.getName()); // 判断是否有Table注解 if (clazz.isAnnotationPresent(Table.class)) { // 获取注解对象 Table table = clazz.getAnnotation(Table.class); // 设置了name属性 if (!table.name().trim().equals("")) { return table.name(); } } return tableName; }
/** * 获取POJO对应的表名 * 需要POJO中的属性定义@Table(name) * @return */ public String tablename() { Table table = this.getClass().getAnnotation(Table.class); if(table != null) return table.name(); else throw new JOPException("undefine POJO @Table, need Tablename(@Table)"); }
private static void registerEntityTypes(Configuration config) { Reflections reflections = new Reflections("pl.mmorpg.prototype.server.database.entities"); Set<Class<?>> entityTypes = reflections.getTypesAnnotatedWith(Table.class); for (Class<?> type : entityTypes) config = config.addAnnotatedClass(type); }
public static String tableName(Class<?> klass) { Table t = klass.getAnnotation(Table.class); if (t != null) { return t.name(); } return klass.getSimpleName(); }
static String getTableName(Class<?> clazz) { Table table = clazz.getAnnotation(Table.class); if (table == null) { return clazz.getSimpleName(); } return table.name().isEmpty() ? clazz.getSimpleName() : table.name(); }
String getTableName(Class<?> clazz) { Table t = clazz.getAnnotation(Table.class); if (t != null && !t.name().isEmpty()) { return t.name(); } return clazz.getSimpleName(); }
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)) { continue; } else 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(); }
private ArrayList<String[]> _getFieldsFromUniqueConstraint(Object value){ ArrayList<String[]> result = new ArrayList<>(); if(value.getClass().isAnnotationPresent(Table.class)){ Table ta = value.getClass().getAnnotation(Table.class); for(UniqueConstraint uc : ta.uniqueConstraints()){ result.add(uc.columnNames()); } } return result; }
public ModelController registerDbOrFileModel(Class<? extends Model> model, Class<? extends ModelController> controller, String bucket) { Table anno = model.getAnnotation(Table.class); if (anno == null) { throw new UsageException("A @Table annotation is required on the model " + model.getCanonicalName() + " in order to register it."); } bucket = or(bucket, anno.name()); String table = anno.name(); DataAccessRegistration registration = new DataAccessRegistration() .setDatabaseBacked(true) .setPersisterClass(DbPersister.class) .setBucket(bucket) .setTableName(table) .setControllerClass(controller) .setStashClass(PartialStash.class) .setModelClass(model); if (!DB.available()) { registration .setDatabaseBacked(false) .setPersisterClass(JsonFilePersister.class) .setStashClass(LocalMemoryStash.class) .setPath(bucket) .setUseDataFolder(true) .setShouldWatch(true) .setWritable(true) ; } return register(registration); }
public static RDBTableMetaData parseMetaDataFromEntity(Class entityClass) { Table table = AnnotationUtils.findAnnotation(entityClass, Table.class); if (table == null) { return null; } RDBTableMetaData tableMetaData = new RDBTableMetaData(); tableMetaData.setName(table.name()); PropertyDescriptor[] descriptors = BeanUtilsBean.getInstance() .getPropertyUtils() .getPropertyDescriptors(entityClass); for (PropertyDescriptor descriptor : descriptors) { Column column = getAnnotation(entityClass, descriptor, Column.class); if (column == null) { continue; } RDBColumnMetaData columnMetaData = new RDBColumnMetaData(); columnMetaData.setName(column.name()); columnMetaData.setAlias(descriptor.getName()); columnMetaData.setLength(column.length()); columnMetaData.setPrecision(column.precision()); columnMetaData.setJavaType(descriptor.getPropertyType()); JDBCType type = jdbcTypeMapping.get(descriptor.getPropertyType()); if (type == null) { type = jdbcTypeConvert.stream() .map(func -> func.apply(entityClass, descriptor)) .filter(Objects::nonNull) .findFirst() .orElse(JDBCType.OTHER); } columnMetaData.setJdbcType(type); tableMetaData.addColumn(columnMetaData); } return tableMetaData; }
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(); }
public static String getTableName(Class<? extends BaseMybatisModel> modelClass) { if (modelClass.isAnnotationPresent(Table.class)) { return ((Table) modelClass.getAnnotation(Table.class)).name(); } if (modelClass.getSuperclass().isAnnotationPresent(Table.class)) { return ((Table) modelClass.getSuperclass().getAnnotation(Table.class)).name(); } return null; }