Getting an entity instance from a public ID or a key

In some cases, your code might not have a reference to an entity instance, but has a reference to one of the following:

The object public ID
A public ID is the PublicID property of an entity instance. Integration code must frequently access objects by using the public ID.
The object key
An object key represents the internal Id property entity instance, which is unique for that entity type. In most cases your code does not access objects by this key. The Id property is the underlying primary key for the object and the contents of a typical foreign key reference. In the underlying database row, this column is just a number. In Gosu, the key object contains both the entity type and the ID value.

To load an entity by a key, use the Bundle method loadBean, which takes a gw.pl.persistence.core.Key object. Create a Key object by using a constructor that takes the entity type and the numeric ID. For example:

var myAddress = gw.transaction.Transaction.getCurrent().loadBean(new Key(Address, 123))

To load an entity by a public ID, use the query builder API. For example:

uses gw.api.database.Query
uses gw.api.database.Relop

var myPublicId = "abc"
var query = Query.make(Policy).compare(Policy#PublicID, Relop.Equals, myPublicId)
        .select().AtMostOneRow

print(query) 

If you use the query builder API, the entity reference that is returned is in a read-only bundle. If you need to modify the data and save changes to the database, you must first add the entity instance to a writable bundle.

See also