ORMlite does not return the object I just saved

Here is my code that fails (it runs inside the action, and the DB helper creates a WishList object 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 essence. The ID field is automatically 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 that the identifier generated in the database does not match the identifier that ORMlite returns in the call below. It returns 1.

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

The identifier in the database is actually 37. Any ideas what I can do wrong? Using version 4.41

+4
source share
1 answer

The ORMLite method Dao.create Dao.create(...) does not return the identifier of the newly created object, but the number of rows in the database that have been changed is usually 1. Here are the javadocs for Dao.create(...) .

Create a new row in the database from the object. If the created object uses DatabaseField.generatedId (), then the data parameter will be changed and set with the corresponding identifier from the database .... Returns: The number of rows updated in the database. It should be 1.

When ORMLite creates an object, the generated identifier is then set to the id field. To find the identifier of your new object, you will 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(); 
+22
source

All Articles