3

我正在尝试扩展基础 ORMLite DAO 类,以便添加一些自定义方法。我试过按照这里的答案,但我得到一个空错误,不知道如何正确地转换 dao 对象(Ormlite - BaseDaoImpl 扩展时构造函数调用失败) 目前,我有下表:

@DatabaseTable(tableName="beers", daoClass=BeerDao.class)
public class Beer {
    public static final String BEER_NAME = "name";

    @DatabaseField(generatedId = true)
    private UUID id = UUID.randomUUID();

    @DatabaseField()
    private String name;

    @DatabaseField()
    private String breweryName;

    public Beer() {}

    ... getters/setters
    }

BeerDao 类:

public class BeerDao<Beer,UUID> extends BaseDaoImpl<Beer,UUID> {

    public BeerDao(ConnectionSource connectionSource, Class<Beer> dataClass) throws SQLException {
        super(connectionSource, dataClass);
    }
}

数据库助手代码:

public class DatabaseHelper extends OrmLiteSqliteOpenHelper  {
    private static final String TAG = "Database";

    private static final String DATABASE_NAME = "brewgenius.db";
    private static final int DATABASE_VERSION = 7;

    private BeerDao<Beer, UUID> beerDao = null;
    private Dao<Checkin, UUID> checkinDao = null;

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION, R.raw.ormlite_config);
    }

    /* ... onCreate and onUpgrade code ..*/

    /**
     * Get Beer Model DAO
     * 
     * @return Beer DAO
     */
    public BeerDao<Beer, UUID> getBeerDao() {
        if (beerDao == null) {
            try {
                beerDao = getDao(Beer.class);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return beerDao;
    }

}

在我的活动中,当我尝试获取 Dao 时,我得到一个空指针异常。

BeerDao<Beer,UUID> dao = getHelper().getBeerDao();

仅供参考,Dao 被投射到:

BeerDao<Beer,UUID>

更新

看起来我的 DatabaseConfigUtil 没有读取 DaoClass 属性。

public class DatabaseConfigUtil extends OrmLiteConfigUtil {
    public static void main(String[] args) throws SQLException, IOException {
        writeConfigFile("ormlite_config.txt");
    }
}

从 DatabaseHelper 的构造函数中删除 ormlite_config.txt 会导致即时读取正确读取 DaoClass 属性。知道作者为什么不写这个吗?

这是 ormlite_config.txt

# --table-start--
dataClass=com.brewgenius.model.Beer
tableName=beers
# --table-fields-start--
# --field-start--
fieldName=id
columnName=_id
generatedId=true
# --field-end--
# --field-start--
fieldName=name
# --field-end--
# --field-start--
fieldName=breweryName
# --field-end--
# --table-fields-end--
# --table-end--
#################################
4

0 回答 0