Room insert “one-to-many” relation
I want to handle "one-to-many" relation using Android Room. I easily can fetch related entities using @Relation[1]. According to [2][3], there isn't native support for @Relation insert in Room. In [3][4] relation is created manually (IDs are set manually for "one" object and related "many" objects). However, I prefer to use Autoincrement PK as id(I access to "one" object by its name(String)).
Is there "elegant way" to insert related entities("one-to-many") with Autoincrement PK?
Links
- https://developer.android.com/reference/android/arch/persistence/room/Relation
- Android Room: Insert relation entities using Room
- https://issuetracker.google.com/issues/62848977
- https://android.jlelse.eu/android-architecture-components-room-relationships-bf473510c14a
android one-to-many android-room
add a comment |
I want to handle "one-to-many" relation using Android Room. I easily can fetch related entities using @Relation[1]. According to [2][3], there isn't native support for @Relation insert in Room. In [3][4] relation is created manually (IDs are set manually for "one" object and related "many" objects). However, I prefer to use Autoincrement PK as id(I access to "one" object by its name(String)).
Is there "elegant way" to insert related entities("one-to-many") with Autoincrement PK?
Links
- https://developer.android.com/reference/android/arch/persistence/room/Relation
- Android Room: Insert relation entities using Room
- https://issuetracker.google.com/issues/62848977
- https://android.jlelse.eu/android-architecture-components-room-relationships-bf473510c14a
android one-to-many android-room
add a comment |
I want to handle "one-to-many" relation using Android Room. I easily can fetch related entities using @Relation[1]. According to [2][3], there isn't native support for @Relation insert in Room. In [3][4] relation is created manually (IDs are set manually for "one" object and related "many" objects). However, I prefer to use Autoincrement PK as id(I access to "one" object by its name(String)).
Is there "elegant way" to insert related entities("one-to-many") with Autoincrement PK?
Links
- https://developer.android.com/reference/android/arch/persistence/room/Relation
- Android Room: Insert relation entities using Room
- https://issuetracker.google.com/issues/62848977
- https://android.jlelse.eu/android-architecture-components-room-relationships-bf473510c14a
android one-to-many android-room
I want to handle "one-to-many" relation using Android Room. I easily can fetch related entities using @Relation[1]. According to [2][3], there isn't native support for @Relation insert in Room. In [3][4] relation is created manually (IDs are set manually for "one" object and related "many" objects). However, I prefer to use Autoincrement PK as id(I access to "one" object by its name(String)).
Is there "elegant way" to insert related entities("one-to-many") with Autoincrement PK?
Links
- https://developer.android.com/reference/android/arch/persistence/room/Relation
- Android Room: Insert relation entities using Room
- https://issuetracker.google.com/issues/62848977
- https://android.jlelse.eu/android-architecture-components-room-relationships-bf473510c14a
android one-to-many android-room
android one-to-many android-room
edited Nov 14 '18 at 14:23
Fantômas
32.4k156388
32.4k156388
asked Nov 14 '18 at 13:23
relativiztrelativizt
11
11
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
I found that @Insert method can return a long, which is the new rowId for the inserted item[1].
If the @Insert method receives only 1 parameter, it can return a long, which is the new rowId for the inserted item. If the parameter is an array or a collection, it should return long or List instead.
And SQLite documentation[2] says:
If a table contains a column of type INTEGER PRIMARY KEY, then that column becomes an alias for the ROWID. You can then access the ROWID using any of four different names, the original three names described above or the name given to the INTEGER PRIMARY KEY column. All these names are aliases for one another and work equally well in any context.
So we can make:
1) CompanyEntity.java
@Entity(tableName = "companies", indices = @Index(value = "name", unique = true)) public class CompanyEntity {
@PrimaryKey (autoGenerate = true)
public int id;
@NonNull
@ColumnInfo(name = "name")
private final String mCompanyName;
public CompanyEntity(@NonNull String companyName) {
mCompanyName = companyName;
}
@NonNull
public String getCompanyName() {
return mCompanyName;
}
}
2) EmployeeEntity.java
@Entity(tableName = "employee_list",
foreignKeys = @ForeignKey(
entity = CompanyEntity.class,
parentColumns = "id",
childColumns = "company_id",
onDelete = CASCADE),
indices = @Index("company_id"))
public class EmployeeEntity {
@PrimaryKey(autoGenerate = true)
public int id;
@ColumnInfo(name = "company_id")
private long mCompanyId;
@NonNull
@ColumnInfo(name = "name")
private final String mName;
public EmployeeEntity(@NonNull String name) {
mName = name;
}
@NonNull
public String getName() {
return mName;
}
public long getCompanyId() {
return mCompanyId;
}
public void setCompanyId(long companyId) {
mCompanyId = companyId;
}
}
3) EmployeeDao.java
@Dao
public abstract class EmployeeDao {
@Query("SELECT * FROM companies")
public abstract List<CompanyEntity> selectAllCompanies();
@Transaction
@Query("SELECT * FROM companies WHERE name LIKE :companyName")
public abstract List<CompanyEmployees> getEmployeesByCompanyName(String companyName);
@Transaction
public void insert(CompanyEntity companyEntity, List<EmployeeEntity> employeeEntities) {
// Save rowId of inserted CompanyEntity as companyId
final long companyId = insert(companyEntity);
// Set companyId for all related employeeEntities
for (EmployeeEntity employeeEntity : employeeEntities) {
employeeEntity.setCompanyId(companyId);
insert(employeeEntity);
}
}
// If the @Insert method receives only 1 parameter, it can return a long,
// which is the new rowId for the inserted item.
// https://developer.android.com/training/data-storage/room/accessing-data
@Insert(onConflict = REPLACE)
public abstract long insert(CompanyEntity company);
@Insert
public abstract void insert(EmployeeEntity employee);
}
It seems to work fine.
Full source code and example project:
https://github.com/relativizt/android-room-one-to-many-auto-pk
Links
- https://developer.android.com/training/data-storage/room/accessing-data
- https://www.sqlite.org/autoinc.html
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53301274%2froom-insert-one-to-many-relation%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
I found that @Insert method can return a long, which is the new rowId for the inserted item[1].
If the @Insert method receives only 1 parameter, it can return a long, which is the new rowId for the inserted item. If the parameter is an array or a collection, it should return long or List instead.
And SQLite documentation[2] says:
If a table contains a column of type INTEGER PRIMARY KEY, then that column becomes an alias for the ROWID. You can then access the ROWID using any of four different names, the original three names described above or the name given to the INTEGER PRIMARY KEY column. All these names are aliases for one another and work equally well in any context.
So we can make:
1) CompanyEntity.java
@Entity(tableName = "companies", indices = @Index(value = "name", unique = true)) public class CompanyEntity {
@PrimaryKey (autoGenerate = true)
public int id;
@NonNull
@ColumnInfo(name = "name")
private final String mCompanyName;
public CompanyEntity(@NonNull String companyName) {
mCompanyName = companyName;
}
@NonNull
public String getCompanyName() {
return mCompanyName;
}
}
2) EmployeeEntity.java
@Entity(tableName = "employee_list",
foreignKeys = @ForeignKey(
entity = CompanyEntity.class,
parentColumns = "id",
childColumns = "company_id",
onDelete = CASCADE),
indices = @Index("company_id"))
public class EmployeeEntity {
@PrimaryKey(autoGenerate = true)
public int id;
@ColumnInfo(name = "company_id")
private long mCompanyId;
@NonNull
@ColumnInfo(name = "name")
private final String mName;
public EmployeeEntity(@NonNull String name) {
mName = name;
}
@NonNull
public String getName() {
return mName;
}
public long getCompanyId() {
return mCompanyId;
}
public void setCompanyId(long companyId) {
mCompanyId = companyId;
}
}
3) EmployeeDao.java
@Dao
public abstract class EmployeeDao {
@Query("SELECT * FROM companies")
public abstract List<CompanyEntity> selectAllCompanies();
@Transaction
@Query("SELECT * FROM companies WHERE name LIKE :companyName")
public abstract List<CompanyEmployees> getEmployeesByCompanyName(String companyName);
@Transaction
public void insert(CompanyEntity companyEntity, List<EmployeeEntity> employeeEntities) {
// Save rowId of inserted CompanyEntity as companyId
final long companyId = insert(companyEntity);
// Set companyId for all related employeeEntities
for (EmployeeEntity employeeEntity : employeeEntities) {
employeeEntity.setCompanyId(companyId);
insert(employeeEntity);
}
}
// If the @Insert method receives only 1 parameter, it can return a long,
// which is the new rowId for the inserted item.
// https://developer.android.com/training/data-storage/room/accessing-data
@Insert(onConflict = REPLACE)
public abstract long insert(CompanyEntity company);
@Insert
public abstract void insert(EmployeeEntity employee);
}
It seems to work fine.
Full source code and example project:
https://github.com/relativizt/android-room-one-to-many-auto-pk
Links
- https://developer.android.com/training/data-storage/room/accessing-data
- https://www.sqlite.org/autoinc.html
add a comment |
I found that @Insert method can return a long, which is the new rowId for the inserted item[1].
If the @Insert method receives only 1 parameter, it can return a long, which is the new rowId for the inserted item. If the parameter is an array or a collection, it should return long or List instead.
And SQLite documentation[2] says:
If a table contains a column of type INTEGER PRIMARY KEY, then that column becomes an alias for the ROWID. You can then access the ROWID using any of four different names, the original three names described above or the name given to the INTEGER PRIMARY KEY column. All these names are aliases for one another and work equally well in any context.
So we can make:
1) CompanyEntity.java
@Entity(tableName = "companies", indices = @Index(value = "name", unique = true)) public class CompanyEntity {
@PrimaryKey (autoGenerate = true)
public int id;
@NonNull
@ColumnInfo(name = "name")
private final String mCompanyName;
public CompanyEntity(@NonNull String companyName) {
mCompanyName = companyName;
}
@NonNull
public String getCompanyName() {
return mCompanyName;
}
}
2) EmployeeEntity.java
@Entity(tableName = "employee_list",
foreignKeys = @ForeignKey(
entity = CompanyEntity.class,
parentColumns = "id",
childColumns = "company_id",
onDelete = CASCADE),
indices = @Index("company_id"))
public class EmployeeEntity {
@PrimaryKey(autoGenerate = true)
public int id;
@ColumnInfo(name = "company_id")
private long mCompanyId;
@NonNull
@ColumnInfo(name = "name")
private final String mName;
public EmployeeEntity(@NonNull String name) {
mName = name;
}
@NonNull
public String getName() {
return mName;
}
public long getCompanyId() {
return mCompanyId;
}
public void setCompanyId(long companyId) {
mCompanyId = companyId;
}
}
3) EmployeeDao.java
@Dao
public abstract class EmployeeDao {
@Query("SELECT * FROM companies")
public abstract List<CompanyEntity> selectAllCompanies();
@Transaction
@Query("SELECT * FROM companies WHERE name LIKE :companyName")
public abstract List<CompanyEmployees> getEmployeesByCompanyName(String companyName);
@Transaction
public void insert(CompanyEntity companyEntity, List<EmployeeEntity> employeeEntities) {
// Save rowId of inserted CompanyEntity as companyId
final long companyId = insert(companyEntity);
// Set companyId for all related employeeEntities
for (EmployeeEntity employeeEntity : employeeEntities) {
employeeEntity.setCompanyId(companyId);
insert(employeeEntity);
}
}
// If the @Insert method receives only 1 parameter, it can return a long,
// which is the new rowId for the inserted item.
// https://developer.android.com/training/data-storage/room/accessing-data
@Insert(onConflict = REPLACE)
public abstract long insert(CompanyEntity company);
@Insert
public abstract void insert(EmployeeEntity employee);
}
It seems to work fine.
Full source code and example project:
https://github.com/relativizt/android-room-one-to-many-auto-pk
Links
- https://developer.android.com/training/data-storage/room/accessing-data
- https://www.sqlite.org/autoinc.html
add a comment |
I found that @Insert method can return a long, which is the new rowId for the inserted item[1].
If the @Insert method receives only 1 parameter, it can return a long, which is the new rowId for the inserted item. If the parameter is an array or a collection, it should return long or List instead.
And SQLite documentation[2] says:
If a table contains a column of type INTEGER PRIMARY KEY, then that column becomes an alias for the ROWID. You can then access the ROWID using any of four different names, the original three names described above or the name given to the INTEGER PRIMARY KEY column. All these names are aliases for one another and work equally well in any context.
So we can make:
1) CompanyEntity.java
@Entity(tableName = "companies", indices = @Index(value = "name", unique = true)) public class CompanyEntity {
@PrimaryKey (autoGenerate = true)
public int id;
@NonNull
@ColumnInfo(name = "name")
private final String mCompanyName;
public CompanyEntity(@NonNull String companyName) {
mCompanyName = companyName;
}
@NonNull
public String getCompanyName() {
return mCompanyName;
}
}
2) EmployeeEntity.java
@Entity(tableName = "employee_list",
foreignKeys = @ForeignKey(
entity = CompanyEntity.class,
parentColumns = "id",
childColumns = "company_id",
onDelete = CASCADE),
indices = @Index("company_id"))
public class EmployeeEntity {
@PrimaryKey(autoGenerate = true)
public int id;
@ColumnInfo(name = "company_id")
private long mCompanyId;
@NonNull
@ColumnInfo(name = "name")
private final String mName;
public EmployeeEntity(@NonNull String name) {
mName = name;
}
@NonNull
public String getName() {
return mName;
}
public long getCompanyId() {
return mCompanyId;
}
public void setCompanyId(long companyId) {
mCompanyId = companyId;
}
}
3) EmployeeDao.java
@Dao
public abstract class EmployeeDao {
@Query("SELECT * FROM companies")
public abstract List<CompanyEntity> selectAllCompanies();
@Transaction
@Query("SELECT * FROM companies WHERE name LIKE :companyName")
public abstract List<CompanyEmployees> getEmployeesByCompanyName(String companyName);
@Transaction
public void insert(CompanyEntity companyEntity, List<EmployeeEntity> employeeEntities) {
// Save rowId of inserted CompanyEntity as companyId
final long companyId = insert(companyEntity);
// Set companyId for all related employeeEntities
for (EmployeeEntity employeeEntity : employeeEntities) {
employeeEntity.setCompanyId(companyId);
insert(employeeEntity);
}
}
// If the @Insert method receives only 1 parameter, it can return a long,
// which is the new rowId for the inserted item.
// https://developer.android.com/training/data-storage/room/accessing-data
@Insert(onConflict = REPLACE)
public abstract long insert(CompanyEntity company);
@Insert
public abstract void insert(EmployeeEntity employee);
}
It seems to work fine.
Full source code and example project:
https://github.com/relativizt/android-room-one-to-many-auto-pk
Links
- https://developer.android.com/training/data-storage/room/accessing-data
- https://www.sqlite.org/autoinc.html
I found that @Insert method can return a long, which is the new rowId for the inserted item[1].
If the @Insert method receives only 1 parameter, it can return a long, which is the new rowId for the inserted item. If the parameter is an array or a collection, it should return long or List instead.
And SQLite documentation[2] says:
If a table contains a column of type INTEGER PRIMARY KEY, then that column becomes an alias for the ROWID. You can then access the ROWID using any of four different names, the original three names described above or the name given to the INTEGER PRIMARY KEY column. All these names are aliases for one another and work equally well in any context.
So we can make:
1) CompanyEntity.java
@Entity(tableName = "companies", indices = @Index(value = "name", unique = true)) public class CompanyEntity {
@PrimaryKey (autoGenerate = true)
public int id;
@NonNull
@ColumnInfo(name = "name")
private final String mCompanyName;
public CompanyEntity(@NonNull String companyName) {
mCompanyName = companyName;
}
@NonNull
public String getCompanyName() {
return mCompanyName;
}
}
2) EmployeeEntity.java
@Entity(tableName = "employee_list",
foreignKeys = @ForeignKey(
entity = CompanyEntity.class,
parentColumns = "id",
childColumns = "company_id",
onDelete = CASCADE),
indices = @Index("company_id"))
public class EmployeeEntity {
@PrimaryKey(autoGenerate = true)
public int id;
@ColumnInfo(name = "company_id")
private long mCompanyId;
@NonNull
@ColumnInfo(name = "name")
private final String mName;
public EmployeeEntity(@NonNull String name) {
mName = name;
}
@NonNull
public String getName() {
return mName;
}
public long getCompanyId() {
return mCompanyId;
}
public void setCompanyId(long companyId) {
mCompanyId = companyId;
}
}
3) EmployeeDao.java
@Dao
public abstract class EmployeeDao {
@Query("SELECT * FROM companies")
public abstract List<CompanyEntity> selectAllCompanies();
@Transaction
@Query("SELECT * FROM companies WHERE name LIKE :companyName")
public abstract List<CompanyEmployees> getEmployeesByCompanyName(String companyName);
@Transaction
public void insert(CompanyEntity companyEntity, List<EmployeeEntity> employeeEntities) {
// Save rowId of inserted CompanyEntity as companyId
final long companyId = insert(companyEntity);
// Set companyId for all related employeeEntities
for (EmployeeEntity employeeEntity : employeeEntities) {
employeeEntity.setCompanyId(companyId);
insert(employeeEntity);
}
}
// If the @Insert method receives only 1 parameter, it can return a long,
// which is the new rowId for the inserted item.
// https://developer.android.com/training/data-storage/room/accessing-data
@Insert(onConflict = REPLACE)
public abstract long insert(CompanyEntity company);
@Insert
public abstract void insert(EmployeeEntity employee);
}
It seems to work fine.
Full source code and example project:
https://github.com/relativizt/android-room-one-to-many-auto-pk
Links
- https://developer.android.com/training/data-storage/room/accessing-data
- https://www.sqlite.org/autoinc.html
answered Nov 18 '18 at 14:30
relativiztrelativizt
11
11
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53301274%2froom-insert-one-to-many-relation%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown