ythy / blog

Give everything a shot
7 stars 0 forks source link

ORMLite Problems #126

Open ythy opened 6 years ago

ythy commented 6 years ago

Official Website 数据库操作API

  1. 生成Config File的路径在项目根目录的./res/raw下, 不是./app/src/main/res/raw下, 需要手动建./res/raw, 生成.txt文件后拷贝到相应目录

    
    public class DatabaseConfigUtil extends OrmLiteConfigUtil {
    
    private static final Class<?>[] classes = new Class[] {
            GameInfo.class,
    };
    
    public static void main(String[] args) throws Exception {
        writeConfigFile("ormlite_config.txt", classes);
    }

}

2. DatabaseField -  id (Boolean)
Default is false. Only one field can have this set in a class. Id fields uniquely identity a row and are required **if you want to use the query, update, refresh, and delete by ID methods**. Only one of this, generatedId, and generatedIdSequence can be specified. See section Fields With id. 

@DatabaseField(id = true, columnName="_id") private int id = -1;

3. `createIfNotExists()` 和 `delete()` 使用的时候,  表必须有列设置 `id field`
4. DatabaseField 字段名区分大小写
5. 每一个`qb.where().XX()` 自带 `AND`, 如下错误:`: Expecting there to be a clause already defined for 'AND' operation`
```java
qb.where().eq(x, 1);
qb.and();
qb.where.eq(y, 2);
  1. 数据库表中的字段, 在表对象(VO)中必须有对应的字段
  2. 表自增id字段的设置 默认值0: 如果表是空的 id = 1, 如果表不是空的 id = Max(id) + 1 自定义值X : id = X
    @DatabaseField(generatedId = true, allowGeneratedIdInsert = true, columnName=ID)
    private int id;
  3. 表对象(vo) 貌似不支持序列化
ythy commented 6 years ago

ORMlite not returning the object I just saved

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();
ythy commented 6 years ago

取count的用法, 关键要 setCountOf(true);

            QueryBuilder<CardInfo, Integer> qbCount = this.queryBuilder();
            qbCount.setCountOf(true);
            qbCount.orderBy(orderBy, isAsc);
            qbCount.selectRaw("*");
            qbCount.setWhere(where);
            int count = (int) this.countOf(qbCount.prepare());