Unique constraint on single String column with GreenDao2

本文探讨了在使用GreenDao框架时如何实现字符串属性的唯一性约束。作者尝试了多种方法,包括使用PropertyBuilder的unique()和index()特性,但遇到了Robolectric测试中的异常问题。最终采用了一种通过查询来避免重复条目的解决方案,并讨论了这种方法是否足够好及是否应该为名称属性添加索引来提高性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转:http://software.techassistbox.com/unique-constraint-on-single-string-column-with-greendao_384521.html

 

I want to make unique constraint on String value with GreenDao. I have following piece of code:

Entity category = schema.addEntity('Category');
category.addIdProperty();
category.addStringProperty('Name').notNull();

How can I make sure that Name will be unique?

My tries:

I have found methods PropertyBuilder.unique() and PropertyBuilder.index() but none of this works.

index() doesn't work at all and allows to make duplication. unique() throws exception in Robolectric test but don't do anything when app runs on device Robolectric exception:

android.database.sqlite.SQLiteException: Cannot execute for last inserted row ID, base error code: 19
    at org.robolectric.shadows.ShadowSQLiteConnection.rethrow(ShadowSQLiteConnection.java:48)
    at org.robolectric.shadows.ShadowSQLiteConnection.access$500(ShadowSQLiteConnection.java:26)
    at org.robolectric.shadows.ShadowSQLiteConnection$Connections.execute(ShadowSQLiteConnection.java:436)
    at org.robolectric.shadows.ShadowSQLiteConnection.nativeExecuteForLastInsertedRowId(ShadowSQLiteConnection.java:239)
    at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(SQLiteConnection.java)
    at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:782)
    at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
    at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
    at de.greenrobot.dao.AbstractDao.executeInsert(AbstractDao.java:348)
    at de.greenrobot.dao.AbstractDao.insert(AbstractDao.java:293)

So far I have made something like this but I don't think it's the best solution. 

However if this correct, is it good idea to add index() to name Property to get better performance?

 

public Long insert(Category category) {
    if (getByName(category.getName()) != null) {
        throw new DuplicateCategoryNameException(category.getName());
    }
    ...
}

public Category getByName(String name) {
    return categoryDao.queryBuilder().where(CategoryDao.Properties.Name.eq(name)).build().unique();
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值