Last active
November 11, 2015 16:29
-
-
Save pflammertsma/de7b8c0fef60c8abc910 to your computer and use it in GitHub Desktop.
Example of using a custom annotation for prefixing Index names
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Define the @IndexPrefixedByTableName annotation: | |
| @Retention(value = RetentionPolicy.RUNTIME) | |
| @Target(value = ElementType.FIELD) | |
| public @interface IndexPrefixedByTableName {} | |
| // In your model, for instance in a superclass of multiple models: | |
| @IndexPrefixedByTableName | |
| @Index(uniqueNames = @CompositeIndex(indexName = "_uuid", order = 0)) | |
| @Column(UUID) | |
| protected String mUuid; | |
| // Where Cupboard is built: | |
| builder.registerEntityConverterFactory(new EntityConverterFactory() { | |
| @Override | |
| public <T> EntityConverter<T> create(Cupboard cupboard, Class<T> type) { | |
| final String tableName = type.getSimpleName(); | |
| return new ReflectiveEntityConverter<T>(cupboard, type) { | |
| @Override | |
| protected Index getIndexes(Field field) { | |
| final Index indexes = super.getIndexes(field); | |
| IndexPrefixedByTableName indexPrefixedByTableName = field | |
| .getAnnotation(IndexPrefixedByTableName.class); | |
| if (indexPrefixedByTableName != null) { | |
| IndexBuilder indexBuilder = new IndexBuilder(); | |
| // Collect all non-unique indices | |
| for (CompositeIndex compositeIndex : indexes.indexNames()) { | |
| IndexBuilder.CompositeIndexBuilder compositeIndexBuilder = indexBuilder | |
| .named(tableName + compositeIndex.indexName()) | |
| .order(compositeIndex.order()); | |
| if (compositeIndex.ascending()) { | |
| compositeIndexBuilder.ascending(); | |
| } else { | |
| compositeIndexBuilder.descending(); | |
| } | |
| } | |
| // Do the same for unique indices | |
| for (CompositeIndex compositeIndex : indexes.uniqueNames()) { | |
| IndexBuilder.CompositeIndexBuilder compositeIndexBuilder = indexBuilder | |
| .named(tableName + compositeIndex.indexName()) | |
| .order(compositeIndex.order()); | |
| if (compositeIndex.ascending()) { | |
| compositeIndexBuilder.ascending(); | |
| } else { | |
| compositeIndexBuilder.descending(); | |
| } | |
| compositeIndexBuilder.unique(); | |
| } | |
| return indexBuilder.build(); | |
| } | |
| return indexes; | |
| } | |
| }; | |
| } | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment