Skip to content

Commit a32a0e5

Browse files
committed
refactor: extract magic number 0L to constant for new entity check
1 parent ec792a2 commit a32a0e5

File tree

2 files changed

+23
-2
lines changed

2 files changed

+23
-2
lines changed

src/main/java/org/springframework/data/repository/core/support/AbstractEntityInformation.java

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
*/
3131
public abstract class AbstractEntityInformation<T, ID> implements EntityInformation<T, ID> {
3232

33+
public static final long NEW_ID = 0L;
3334
private final Class<T> domainClass;
3435

3536
public AbstractEntityInformation(Class<T> domainClass) {
@@ -50,7 +51,7 @@ public boolean isNew(T entity) {
5051
}
5152

5253
if (id instanceof Number n) {
53-
return n.longValue() == 0L;
54+
return n.longValue() == NEW_ID;
5455
}
5556

5657
throw new IllegalArgumentException(String.format("Unsupported primitive id type %s", idType));

src/test/java/org/springframework/data/repository/core/support/AbstractEntityInformationUnitTests.java

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ void considersEntityNewIfGetIdReturnsNull() throws Exception {
4949
}
5050

5151
@Test // DATACMNS-357
52-
void detectsNewStateForPrimitiveIds() {
52+
void detectsNewStateForZeroIds() {
5353

5454
var fooEn = new CustomEntityInformation<PrimitiveIdEntity, Serializable>(
5555
PrimitiveIdEntity.class);
@@ -61,6 +61,16 @@ void detectsNewStateForPrimitiveIds() {
6161
assertThat(fooEn.isNew(entity)).isFalse();
6262
}
6363

64+
@Test // DATACMNS-357
65+
void detectsNewStateForPrimitiveIds() {
66+
67+
var fooEn = new CustomEntityInformation<PrimitiveWithIdEntity, Serializable>(
68+
PrimitiveWithIdEntity.class);
69+
70+
var entity = new PrimitiveWithIdEntity(0L);
71+
assertThat(fooEn.isNew(entity)).isTrue();
72+
}
73+
6474
@Test // DATACMNS-357
6575
void detectsNewStateForPrimitiveWrapperIds() {
6676

@@ -85,6 +95,16 @@ void rejectsUnsupportedPrimitiveIdType() {
8595
.withMessageContaining(boolean.class.getName());
8696
}
8797

98+
static class PrimitiveWithIdEntity {
99+
100+
@Id long id;
101+
102+
103+
public PrimitiveWithIdEntity(long id) {
104+
this.id = id;
105+
}
106+
}
107+
88108
static class PrimitiveIdEntity {
89109

90110
@Id long id;

0 commit comments

Comments
 (0)