Skip to content

Instantly share code, notes, and snippets.

@rcketscientist
Last active December 31, 2017 21:27
Show Gist options
  • Save rcketscientist/53cbdab925fcaa7dc9850375160e023b to your computer and use it in GitHub Desktop.
Save rcketscientist/53cbdab925fcaa7dc9850375160e023b to your computer and use it in GitHub Desktop.
Quick glance that demonstrates generating a proper Room object model including an M:N junction table. This could probably be done more efficiently. Ideally @relation could walk through ForeignKey avoiding all this nonsense. M:N "List<String>" is GROUP_CONCAT to reduce the result to single entities, then the keyword is split with a TypeConverter.
@Dao
public abstract class MetadataDao {
@Query("SELECT id, name, type, height, width, orientation, " +
"(SELECT GROUP_CONCAT(name) " +
"FROM meta_subject_junction " +
"JOIN xmp_subject " +
"ON xmp_subject.id = meta_subject_junction.subjectId " +
"WHERE meta_subject_junction.metaId = meta.id) AS keywords, " +
"(SELECT documentUri " +
"FROM image_parent " +
"WHERE meta.parentId = image_parent.id ) AS parentUri " +
"FROM meta")
abstract LiveData<List<MetadataResult>> getImages();
}
@TypeConverters({MetadataResult.class})
public class MetadataResult extends MetadataEntity {
public List<String> keywords;
public String parentUri;
@TypeConverter
public List<String> fromGroupConcat(String keywords) {
return Arrays.asList(keywords.split(","));
}
}
@Entity(tableName = "xmp_subject",
indices = @Index(value = "id"))
public class SubjectEntity extends PathEntity
{
SubjectEntity() {}
SubjectEntity(String path, int depth, long parent, String name, Long recent)
{
super(path, depth, parent);
this.name = name;
this.recent = recent;
}
SubjectEntity(Long id, String path, int depth, long parent, String name, Long recent)
{
super(id, path, depth, parent);
this.name = name;
this.recent = recent;
}
public String name;
public Long recent;
}
@Entity(
tableName = "meta_subject_junction",
primaryKeys = {"metaId", "subjectId"},
indices = {
@Index(value = "subjectId"),
@Index(value = "metaId")},
foreignKeys = {
@ForeignKey(
entity = MetadataEntity.class,
parentColumns = "id",
childColumns = "metaId",
onDelete = CASCADE),
@ForeignKey(
entity = SubjectEntity.class,
parentColumns = "id",
childColumns = "subjectId",
onDelete = CASCADE)})
public class SubjectJunction {
public SubjectJunction(@NonNull Long metaId, @NonNull Long subjectId) {
this.metaId = metaId;
this.subjectId = subjectId;
}
@NonNull
public Long metaId;
@NonNull
public Long subjectId;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment