views:

32

answers:

2

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.

+1  A: 

Whats wrong with IdGeneratorStrategy.SEQUENCE ? since GAE/J claims to support it

DataNucleus
Just as with `IdGeneratorStrategy.IDENTITY`, the sequence is unique within individual fetch groups but not across the application.
Jimi
I think you mean Entity Groups (a GAE/J BigTable concept). A FetchGroup is a group of fields used when retrieving using JDO. If their sequence is not unique across the app then request them to fix it so it is (or at least is an option)
DataNucleus
Yes, you're right. I can see after reading Nick Johnson's response that I misunderstood the source of the problem and it is actually an Entity Group issue and not a Fetch Group issue. At least that's progress of sorts.
Jimi
+1  A: 

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?

Nick Johnson
Jimi
Why not just make the questions root entities, with a ReferenceProperty to the user that posted them, rather than making them child entities, then?
Nick Johnson
Not sure why I didn't think of that. I just naturally thought of them as child entities. But I guess they don't need to be. Thanks.
Jimi