Skip to content

Commit

Permalink
Add TxnIdGenerator
Browse files Browse the repository at this point in the history
ar committed Jan 19, 2025
1 parent f9e03ab commit d170054
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions modules/dbsupport/src/main/java/org/jpos/ee/TxnIdGenerator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package org.jpos.ee;

import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.IdentifierGenerator;
import org.jpos.q2.Q2;
import org.jpos.transaction.TxnId;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.time.Instant;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

@SuppressWarnings("unused")
public class TxnIdGenerator implements IdentifierGenerator {
private static final int nodeId;
private static final ConcurrentMap<Class<?>, Class<?>> idFieldTypeCache = new ConcurrentHashMap<>();

static {
nodeId = Q2.getQ2().node();
}
@Override
public Serializable generate(SharedSessionContractImplementor session, Object object) {
Class<?> entityClass = object.getClass();
Class<?> idType = idFieldTypeCache.computeIfAbsent(entityClass, cls -> {
try {
Field idField = cls.getDeclaredField("id");
idField.setAccessible(true); // Access private fields if necessary
return idField.getType();
} catch (NoSuchFieldException e) {
throw new RuntimeException("Failed to determine ID field type for entity: " + cls.getName(), e);
}
});
TxnId txnId = TxnId.create(Instant.now(), nodeId, System.nanoTime());
if (idType.equals(String.class)) {
return txnId.toString();
} else if (idType.equals(Long.class)) {
return txnId.id();
} else {
throw new UnsupportedOperationException("Unsupported ID type: " + idType);
}
}
}

0 comments on commit d170054

Please sign in to comment.