Skip to content

Commit c8c92a0

Browse files
committed
added ToMany.removeById()
1 parent ffffd1e commit c8c92a0

File tree

2 files changed

+35
-1
lines changed
  • objectbox-java/src/main/java/io/objectbox/relation
  • tests/objectbox-java-test/src/main/java/io/objectbox/relation

2 files changed

+35
-1
lines changed

objectbox-java/src/main/java/io/objectbox/relation/ToMany.java

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -327,6 +327,26 @@ public synchronized boolean remove(Object object) {
327327
return removed;
328328
}
329329

330+
@Beta
331+
/** Removes an object by its entity ID. */
332+
public synchronized TARGET removeById(long id) {
333+
ensureEntities();
334+
int size = entities.size();
335+
IdGetter<TARGET> idGetter = relationInfo.targetInfo.getIdGetter();
336+
for (int i = 0; i < size; i++) {
337+
TARGET candidate = entities.get(i);
338+
if (idGetter.getId(candidate) == id) {
339+
TARGET removed = remove(i);
340+
if (removed != candidate) {
341+
throw new IllegalStateException("Mismatch: " + removed + " vs. " + candidate);
342+
}
343+
return candidate;
344+
}
345+
346+
}
347+
return null;
348+
}
349+
330350
@Override
331351
public synchronized boolean removeAll(Collection<?> objects) {
332352
boolean changes = false;
@@ -518,7 +538,7 @@ public boolean hasA(QueryFilter<TARGET> filter) {
518538
public boolean hasAll(QueryFilter<TARGET> filter) {
519539
ensureEntities();
520540
Object[] objects = entities.toArray();
521-
if(objects.length == 0) {
541+
if (objects.length == 0) {
522542
return false;
523543
}
524544
for (Object target : objects) {

tests/objectbox-java-test/src/main/java/io/objectbox/relation/ToManyTest.java

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,20 @@ public void testRemoveAll() {
187187
assertOrder2And4Removed(count, customer, toMany);
188188
}
189189

190+
@Test
191+
public void testRemoveById() {
192+
int count = 5;
193+
Customer customer = putCustomerWithOrders(count);
194+
ToMany<Order> toMany = (ToMany<Order>) customer.orders;
195+
Order removed1 = toMany.removeById(toMany.get(3).getId());
196+
assertEquals("order4", removed1.getText());
197+
Order removed2 = toMany.removeById(toMany.get(1).getId());
198+
assertEquals("order2", removed2.getText());
199+
assertNull(toMany.removeById(42));
200+
customerBox.put(customer);
201+
assertOrder2And4Removed(count, customer, toMany);
202+
}
203+
190204
@Test
191205
public void testRetainAll() {
192206
int count = 5;

0 commit comments

Comments
 (0)