How to configure a JDO transaction to simulate creating a database sequence in App Engine Java?
This syntax does not produce unique values across different Fetch Groups:
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private long id;
So I've written the method below to simulate generating a database sequence for my Order model. But what I'm not sure about is what the transactional state needs to be configured as here (isolation level / nontransactional read / nontransactional write / optimistic / etc.
):
public long getNextId()
{
PersistenceManager pm = this.getPm();
Transaction tx = pm.currentTransaction();
tx.begin();
long nextId = 0;
Query query = pm.newQuery("select id from orders order by id desc");
query.setRange(0, 1);
try
{
List<Order> results = (List<Order>) query.execute();
if (results.iterator().hasNext())
{
for (Order r : results)
{
nextId = r.getId() + 1;
}
}
else
{
return 0;
}
}
catch (Exception e)
{
return 0;
}
tx.commit();
return nextId;
}
Does the 开发者_开发技巧scope of the transaction need to be broader than just this method? In other words, should it also include the insert action for the new Order?
I want to make sure that no two Orders that I insert can have the same id value across the entire application.
IDs generated with IdGeneratorStrategy.SEQUENCE are unique for all entities with the same parent. If your entities are root entities (Eg, no parent), then they will all get unique IDs. What is your use case where you have child entities, but need a unique ID across all of them?
Whats wrong with IdGeneratorStrategy.SEQUENCE ? since GAE/J claims to support it
精彩评论