File tree Expand file tree Collapse file tree 2 files changed +33
-0
lines changed
objectbox-java/src/main/java/io/objectbox/relation
tests/objectbox-java-test/src/main/java/io/objectbox/relation Expand file tree Collapse file tree 2 files changed +33
-0
lines changed Original file line number Diff line number Diff line change @@ -72,6 +72,7 @@ public class ToMany<TARGET> implements List<TARGET>, Serializable {
72
72
transient private Box entityBox ;
73
73
transient private volatile Box <TARGET > targetBox ;
74
74
transient private boolean removeFromTargetBox ;
75
+ transient private Comparator <TARGET > comparator ;
75
76
76
77
public ToMany (Object sourceEntity , RelationInfo <TARGET > relationInfo ) {
77
78
if (sourceEntity == null ) {
@@ -93,6 +94,12 @@ public void setListFactory(ListFactory listFactory) {
93
94
this .listFactory = listFactory ;
94
95
}
95
96
97
+ /** Set an comparator to define the order of entities. */
98
+ @ Experimental
99
+ public void setComparator (Comparator <TARGET > comparator ) {
100
+ this .comparator = comparator ;
101
+ }
102
+
96
103
/**
97
104
* On put, this also deletes removed entities from the target Box.
98
105
* Note: removed target entities won't cascade the delete.
@@ -162,6 +169,9 @@ private void ensureEntities() {
162
169
newEntities = targetBox .internalGetBacklinkEntities (relationInfo .targetInfo .getEntityId (),
163
170
relationInfo .targetIdProperty , id );
164
171
}
172
+ if (comparator != null ) {
173
+ Collections .sort (newEntities , comparator );
174
+ }
165
175
synchronized (this ) {
166
176
if (entities == null ) {
167
177
entities = newEntities ;
Original file line number Diff line number Diff line change 18
18
19
19
import org .junit .Test ;
20
20
21
+ import java .util .Comparator ;
21
22
import java .util .List ;
22
23
23
24
import io .objectbox .query .Query ;
@@ -55,6 +56,28 @@ public void testRelationToMany() {
55
56
assertEquals ("Oranges" , orders .get (1 ).getText ());
56
57
}
57
58
59
+ @ Test
60
+ public void testRelationToMany_comparator () {
61
+ Customer customer = putCustomer ();
62
+ putOrder (customer , "Bananas" );
63
+ putOrder (customer , "Oranges" );
64
+ putOrder (customer , "Apples" );
65
+
66
+ ToMany <Order > orders = (ToMany <Order >) customer .getOrders ();
67
+ orders .setComparator (new Comparator <Order >() {
68
+ @ Override
69
+ public int compare (Order o1 , Order o2 ) {
70
+ return o1 .text .compareTo (o2 .text );
71
+ }
72
+ });
73
+ orders .reset ();
74
+
75
+ assertEquals (3 , orders .size ());
76
+ assertEquals ("Apples" , orders .get (0 ).getText ());
77
+ assertEquals ("Bananas" , orders .get (1 ).getText ());
78
+ assertEquals ("Oranges" , orders .get (2 ).getText ());
79
+ }
80
+
58
81
@ Test
59
82
public void testRelationToMany_activeRelationshipChanges () {
60
83
Customer customer = putCustomer ();
You can’t perform that action at this time.
0 commit comments