-
Notifications
You must be signed in to change notification settings - Fork 153
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Loading status checks…
Add TxnIdGenerator
Showing
1 changed file
with
43 additions
and
0 deletions.
There are no files selected for viewing
43 changes: 43 additions & 0 deletions
43
modules/dbsupport/src/main/java/org/jpos/ee/TxnIdGenerator.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
} | ||
} |