Skip to content

armgit / core

Public Imported from GitHub
0

100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps

Gradle task to validate equals and hashcode methods in jpa entities (#1852)

Thilakshi Hansini630cb34f5178
diff --git a/build.gradle b/build.gradle
index 7831098cf..68209b856 100644
--- a/build.gradle
+++ b/build.gradle
@@ -80,3 +80,59 @@ tasks.register('clean') {
delete 'tmp'
}
}
+
+
+buildscript {
+ repositories {
+ mavenCentral()
+ }
+ dependencies {
+ classpath 'org.ow2.asm:asm:9.5'
+ classpath 'org.ow2.asm:asm-tree:9.5'
+ }
+}
+
+subprojects {
+ afterEvaluate { proj ->
+ if (proj.plugins.hasPlugin('java')) {
+ def entityAnnotation = 'Ljakarta/persistence/Entity;'
+
+ proj.tasks.register('checkJpaEntitiesEquality') {
+ group = 'verification'
+ description = 'Ensure all JPA entities implement equals() and hashCode()'
+ dependsOn proj.tasks.named('classes')
+
+ doLast {
+ proj.sourceSets.main.output.classesDirs.each { dir ->
+ if (!dir.exists()) return
+
+ dir.eachFileRecurse { file ->
+ if (file.name.endsWith('.class')) {
+ def reader = new org.objectweb.asm.ClassReader(file.bytes)
+ def classNode = new org.objectweb.asm.tree.ClassNode()
+ reader.accept(classNode, 0)
+
+ def isEntity = classNode.visibleAnnotations?.any {
+ it.desc == entityAnnotation
+ }
+
+ if (isEntity) {
+ def methodNames = classNode.methods*.name
+ def className = classNode.name.replace('/', '.')
+
+ def missing = []
+ if (!methodNames.contains('equals')) missing << 'equals()'
+ if (!methodNames.contains('hashCode')) missing << 'hashCode()'
+
+ if (!missing.isEmpty()) {
+ println "❌ Entity $className is missing: ${missing.join(', ')}"
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/model/src/main/java/org/openremote/model/asset/Asset.java b/model/src/main/java/org/openremote/model/asset/Asset.java
index 688dec3f1..b2d176d13 100644
--- a/model/src/main/java/org/openremote/model/asset/Asset.java
+++ b/model/src/main/java/org/openremote/model/asset/Asset.java
@@ -622,4 +622,17 @@ public abstract class Asset<T extends Asset<?>> implements IdentifiableEntity<T>
}));
}
}
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ Asset<?> asset = (Asset<?>) o;
+ return version == asset.version && accessPublicRead == asset.accessPublicRead && Objects.equals(id, asset.id) && Objects.equals(createdOn, asset.createdOn) && Objects.equals(name, asset.name) && Objects.equals(parentId, asset.parentId) && Objects.equals(realm, asset.realm) && Objects.equals(type, asset.type) && Objects.deepEquals(path, asset.path) && Objects.equals(attributes, asset.attributes);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(id, version, createdOn, name, accessPublicRead, parentId, realm, type, Arrays.hashCode(path), attributes);
+ }
}