public static String getEntityName(Class entity) { if (mappedName.get(entity) != null) { return mappedName.get(entity); } String name = null; Table table = (Table) entity.getAnnotation(Table.class); if (table != null && table.name() != null && !table.name().isEmpty()) { name = table.name(); } else { Entity entityAnnotation = (Entity) entity.getAnnotation(Entity.class); if (entityAnnotation != null && entityAnnotation.name() != null && !entityAnnotation.name().isEmpty()) { name = entityAnnotation.name(); } else { name = entity.getSimpleName(); } } mappedName.put(entity, name); return name; }
private void putTableDeclaration(AnnotationInfo ai, Class<?> c) { Table table = c.getAnnotation(Table.class); if (table != null) { if (table.name() == null) throw new PersistenceException("You must specify a name= for @Table on " + c.getName()); ai.setDomainName(table.name()); } }
private String buildInsertStatement() { StringBuilder sql = new StringBuilder(); sql.append("insert into ").append(into.name()); sql.append("(").append(JDBC.asString(into.columnNames())).append(")"); sql.append(" values(").append(JDBC.asString(parametersFor(into.columnNames()))).append(")"); return sql.toString(); }
/** * 创建数据库表 * * @return */ private String createTableSQL() { String sql = "create table if not exists " + mTable.name() + "("; Field[] fields = mClazz.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { Column column = fields[i].getAnnotation(Column.class); if (column == null) { continue; } sql += column.name(); if (column.type() == DataType.INT) { sql += " integer"; } else if (column.type() == DataType.LONG) { sql += " long"; } else if (column.type() == DataType.TEXT) { sql += " text"; } if (column.key()) { sql += " primary key autoincrement"; } if (!TextUtils.isEmpty(column.dvalue())) { sql += " default " + column.dvalue(); } if (i < fields.length - 1) { sql += ","; } } sql += ")"; return sql; }
private int indexIn(ResultSet rs) throws SQLException { ResultSetMetaData metaData = rs.getMetaData(); for (int index = 1; index <= metaData.getColumnCount(); index++) { if (metaData.getColumnName(index).equals(name) && metaData.getTableName(index).equals(table.name())) return index; } throw new SQLException("Result set has no column '" + name + "'"); }
/** * 查询按照指定属性值 * * @param t * @param fields * @return * @throws IllegalAccessException * @throws IllegalArgumentException * @throws InstantiationException */ public List<T> query(T t, Field... fields) throws IllegalAccessException, IllegalArgumentException, InstantiationException { String where = " where 1=1"; for (Field field : fields) { Column column = field.getAnnotation(Column.class); if (column.type() == DataType.INT) { where += " and " + column.name() + "=" + field.getInt(t); } else if (column.type() == DataType.LONG) { where += " and " + column.name() + "=" + field.getLong(t); } else if (column.type() == DataType.TEXT) { where += " and " + column.name() + "=" + "'" + field.get(t) + "'"; } } String sql = "select * from " + mTable.name() + where; return query(sql); }
/** * 更新数据库 * * @param t * @param id * @throws IllegalAccessException * @throws IllegalArgumentException */ public void update(T t, int id) throws IllegalAccessException, IllegalArgumentException { ContentValues values = parseXtoContentValues(t); SQLiteDatabase db = getWritableDatabase(); String[] whereArgs = {id + ""}; db.update(mTable.name(), values, "_id=?", whereArgs); }
/** * 插入一条数据 * * @param t * @throws IllegalAccessException * @throws IllegalArgumentException */ public void insert(T t) throws IllegalAccessException, IllegalArgumentException { ContentValues values = parseXtoContentValues(t); SQLiteDatabase db = getWritableDatabase(); db.insert(mTable.name(), null, values); }
/** * 删除 * * @param id */ public void delete(int id) { SQLiteDatabase db = getWritableDatabase(); String[] whereArgs = {id + ""}; db.delete(mTable.name(), "_id=?", whereArgs); }
/** * 获取全部内容 * * @return * @throws IllegalAccessException * @throws InstantiationException */ public List<T> query() throws InstantiationException, IllegalAccessException { String sql = "select * from " + mTable.name(); return query(sql); }
@Override public SqlBuilder accept(SqlBuilder sql) { return sql.identifier(table.name(), name); }
// Not concerned too much about reflective annotation access in this // method, since this only runs once per model class... static EntityMapping build(Class<? extends Entity> clz) { EntityMapping mapping = new EntityMapping(); mapping.mMappedClass = clz; Table table = clz.getAnnotation(Table.class); if (table != null) { mapping.mTableName = table.name(); } else { mapping.mTableName = MATCH_DOTDOLLAR.matcher(clz.getName()).replaceAll(""); } ArrayList<String> seenFields = new ArrayList<String>(); for (Field f : clz.getFields()) { // Blithely ignore this field if we've already seen one with same name - // Java field hiding allows this to happen and if it does, without this // we'd be adding the same column name twice. // // We might as well also ignore it here if it's inverse, since we'll // never want to access it via the mapping. Column colAnn = f.getAnnotation(Column.class); boolean inverse = colAnn != null && colAnn.inverse(); if (!seenFields.contains(f.getName()) && !inverse) { Column col = f.getAnnotation(Column.class); String name; if (col != null) { // empty is default, means we should use field name... if ("".equals(name = col.name())) { name = f.getName(); } if (col.primaryKey()) { mapping.mPrimaryKey = f; mapping.mPrimaryKeyColumnName = name; } } else { name = f.getName(); } // Try to default primary key if we don't have one yet... if (mapping.mPrimaryKey == null) { if ("_id".equals(name) || "id".equals(name)) { mapping.mPrimaryKey = f; mapping.mPrimaryKeyColumnName = name; } } mapping.mFields.add(f); mapping.mColumnNames.add(name); seenFields.add(f.getName()); } } if (mapping.mPrimaryKey == null) { // Error at this point - we must have a primary key! Log.e(TAG, "No primary key specified or determined for " + clz); throw new ORMDroidException( "No primary key was specified, and a default could not be determined for " + clz); } return mapping; }
private AnnotatedRecordMapper(final Class<T> cls) { Table table = cls.getAnnotation(Table.class); if (table == null) { throw new MappingException("Type is missing @Table annotation: " + cls); } tableName = table.name(); List<Accessor> accessors = getAnnotatedAccessors(cls, null, hs.mediasystem.db.Column.class, Id.class); for (Accessor accessor : accessors) { Id id = accessor.getAnnotation(Id.class); hs.mediasystem.db.Column column = accessor.getAnnotation(hs.mediasystem.db.Column.class); @SuppressWarnings("unchecked") Class<DataTypeConverter<Object, Object>> dataTypeConverterClass = (Class<DataTypeConverter<Object, Object>>) (column == null ? DefaultConverter.class : column.converterClass()); if (id != null && idColumn != null) { throw new IllegalStateException("only one @Id annotation allowed: " + cls); } if (accessor.getType().getAnnotation(Embeddable.class) != null) { int embeddableColumnCount = getAnnotatedAccessors(accessor.getType(), null, EmbeddableColumn.class).size(); if (column == null || column.name() == null || column.name().length != embeddableColumnCount) { throw new IllegalArgumentException( "Column annotation for Embeddable field '" + accessor.getName() + "' missing or must specify same number of column names (" + embeddableColumnCount + ") as the embeddable object: " + cls); } } Column c = new Column(column, accessor, dataTypeConverterClass); if (id != null) { idColumn = c; } else if (column != null) { columns.add(c); } if (isRelation(accessor.getType())) { relations.put(accessor.getType(), c.getNames()); } } Collections.sort( columns, new Comparator<Column>() { @Override public int compare(Column o1, Column o2) { String[] names1 = o1.getNames(); String[] names2 = o2.getNames(); int result = Integer.compare(names1.length, names2.length); if (result == 0) { for (int i = 0; i < names1.length; i++) { result = names1[i].compareTo(names2[i]); if (result != 0) { return result; } } throw new MappingException( "Columns cannot share the same set of fields (" + o1 + ") and (" + o2 + "): " + cls); } return result; } }); try { afterLoadStore = MethodHandles.lookup() .findVirtual( cls, "afterLoadStore", MethodType.methodType(void.class, Database.class)); } catch (NoSuchMethodException | IllegalAccessException e) { // ignore and continue } }