Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ORMlite not returning the object I just saved

Here is my code that fails ( it is running within an activity and the DB helper creates the WishList object fine in the database )

DatabaseHelper helper = DatabaseHelper.getInstance( getActivity() );
int savedID = 0;
WishList wl = new WishList();
wl.setName("abc");
try {
    savedID = helper.getWishListDao().create(wl);
    WishList wl_saved = helper.getWishListDao().queryForId( savedID );
    wl_saved.getId();
} catch (SQLException e) {
    e.printStackTrace();
}

Here is my entity. The ID field is auto generated.

@DatabaseTable
public class WishList {
    @DatabaseField(generatedId = true)
    private int id;

    @DatabaseField( canBeNull = false , unique = true )
    private String name;

    @ForeignCollectionField
    private ForeignCollection<WishItem> items;
    ...

What is wrong is the ID that is generated in the Database is not the same one that that ORMlite returns in the call below. It returns 1.

 savedID = helper.getWishListDao().create(wl);

The ID in the database is actually 37. Any ideas what I may be doing wrong? Using version 4.41

like image 300
MayoMan Avatar asked Nov 29 '22 02:11

MayoMan


1 Answers

ORMLite's Dao.create(...) method does not return the ID of the newly created object but the number of rows in the database that were changed – usually 1. Here are the javadocs for Dao.create(...).

Create a new row in the database from an object. If the object being created uses DatabaseField.generatedId() then the data parameter will be modified and set with the corresponding id from the database. ... Returns: The number of rows updated in the database. This should be 1.

When ORMLite creates the object, the generated ID is then set to the id field afterwards. To find the ID of your new object you get it from the object itself:

// create returns 1 row changed
helper.getWishListDao().create(wl);
// the id field is set on the w1 object after it was created
savedID = w1.getId();
like image 90
Gray Avatar answered Dec 04 '22 21:12

Gray