Giter Site home page Giter Site logo

requery / requery Goto Github PK

View Code? Open in Web Editor NEW
3.1K 3.1K 244.0 2.86 MB

requery - modern SQL based query & persistence for Java / Kotlin / Android

License: Apache License 2.0

Java 86.14% Kotlin 13.86%
android java jdbc kotlin mysql oracle persistence postgres rxjava sql sqlite

requery's Introduction

requery

A light but powerful object mapping and SQL generator for Java/Kotlin/Android with RxJava and Java 8 support. Easily map to or create databases, perform queries and updates from any platform that uses Java.

Build Status Download

Examples

Define entities from an abstract class:

@Entity
abstract class AbstractPerson {

    @Key @Generated
    int id;

    @Index("name_index")                     // table specification
    String name;

    @OneToMany                               // relationships 1:1, 1:many, many to many
    Set<Phone> phoneNumbers;

    @Converter(EmailToStringConverter.class) // custom type conversion
    Email email;

    @PostLoad                                // lifecycle callbacks
    void afterLoad() {
        updatePeopleList();
    }
    // getter, setters, equals & hashCode automatically generated into Person.java
}

or from an interface:

@Entity
public interface Person {

    @Key @Generated
    int getId();

    String getName();

    @OneToMany
    Set<Phone> getPhoneNumbers();

    String getEmail();
}

or use immutable types such as those generated by @AutoValue:

@AutoValue
@Entity
abstract class Person {

    @AutoValue.Builder
    static abstract class Builder {
        abstract Builder setId(int id);
        abstract Builder setName(String name);
        abstract Builder setEmail(String email);
        abstract Person build();
    }

    static Builder builder() {
        return new AutoValue_Person.Builder();
    }

    @Key
    abstract int getId();

    abstract String getName();
    abstract String getEmail();
}

(Note some features will not be available when using immutable types, see here)

Queries: dsl based query that maps to SQL

Result<Person> query = data
    .select(Person.class)
    .where(Person.NAME.lower().like("b%")).and(Person.AGE.gt(20))
    .orderBy(Person.AGE.desc())
    .limit(5)
    .get();

Relationships: represent relations more efficiently with Java 8 Streams, RxJava Observables or plain iterables. (sets and lists are supported to)

@Entity
abstract class AbstractPerson {

    @Key @Generated
    int id;

    @ManyToMany
    Result<Group> groups;
    // equivalent to:
    // data.select(Group.class)
    // .join(Group_Person.class).on(Group_ID.equal(Group_Person.GROUP_ID))
    // .join(Person.class).on(Group_Person.PERSON_ID.equal(Person.ID))
    // .where(Person.ID.equal(id))
}

Kotlin specific support using property references and infix functions:

data {
    val result = select(Person::class) where (Person::age gt 21) and (Person::name eq "Bob") limit 10
}

Java 8 streams:

data.select(Person.class)
    .orderBy(Person.AGE.desc())
    .get()
    .stream().forEach(System.out::println);

Java 8 optional and time support:

public interface Person {

    @Key @Generated
    int getId();

    String getName();
    Optional<String> getEmail();
    ZonedDateTime getBirthday();
}

RxJava Observables:

Observable<Person> observable = data
    .select(Person.class)
    .orderBy(Person.AGE.desc())
    .get()
    .observable();

RxJava observe query on table changes:

Observable<Person> observable = data
    .select(Person.class)
    .orderBy(Person.AGE.desc())
    .get()
    .observableResult().subscribe(::updateFromResult);

Read/write separation Along with immutable types optionally separate queries (reading) and updates (writing):

int rows = data.update(Person.class)
    .set(Person.ABOUT, "student")
    .where(Person.AGE.lt(21)).get().value();

Features

  • No Reflection
  • Fast startup & performance
  • No dependencies (RxJava is optional)
  • Typed query language
  • Table generation
  • Supports JDBC and most popular databases (MySQL, Oracle, SQL Server, Postgres and more)
  • Supports Android (SQLite, RecyclerView, Databinding, SQLCipher)
  • Blocking and non-blocking API
  • Partial objects/refresh
  • Upsert support
  • Caching
  • Lifecycle callbacks
  • Custom type converters
  • Compile time entity validation
  • JPA annotations (however requery is not a JPA provider)

Reflection free

requery uses compile time annotation processing to generate entity model classes and mapping attributes. On Android this means you get about the same performance reading objects from a query as if it was populated using the standard Cursor and ContentValues API.

Query with Java

The compiled classes work with the query API to take advantage of compile time generated attributes. Create type safe queries and avoid hard to maintain, error prone string concatenated queries.

Relationships

You can define One-to-One, One-to-Many, Many-to-One, and Many-to-Many relations in your models using annotations. Relationships can be navigated in both directions. Of many type relations can be loaded into standard java collection objects or into a more efficient Result type. From a Result easily create a Stream, RxJava Observable, Iterator, List or Map.

Many-to-Many junction tables can be generated automatically. Additionally the relation model is validated at compile time eliminating runtime errors.

vs JPA

requery provides a modern set of interfaces for persisting and performing queries. Some key differences between requery and JPA providers like Hibernate or EclipseLink:

  • Queries maps directly to SQL as opposed to JPQL.
  • Dynamic Queries easily done through a DSL as opposed to the verbose CriteriaQuery API.
  • Uses easily understandable extended/generated code instead of reflection/bytecode weaving for state tracking and member access

Android

Designed specifically with Android support in mind. See requery-android/example for an example Android project using databinding and interface based entities. For more information see the Android page.

Supported Databases

Tested on some of the most popular databases:

  • PostgresSQL (9.1+)
  • MySQL 5.x
  • Oracle 12c+
  • Microsoft SQL Server 2012 or later
  • SQLite (Android or with the xerial JDBC driver)
  • Apache Derby 10.11+
  • H2 1.4+
  • HSQLDB 2.3+

JPA Annotations

A subset of the JPA annotations that map onto the requery annotations are supported. See here for more information.

Upserts

Upserts are generated with the appropriate database specific query statements:

  • Oracle/SQL Server/HSQL: merge into when matched/not matched
  • PostgresSQL: on conflict do update (requires 9.5 or later)
  • MySQL: on duplicate key update

Using it

Versions are available on bintray jcenter / maven central.

repositories {
    jcenter()
}

dependencies {
    compile 'io.requery:requery:1.6.1'
    compile 'io.requery:requery-android:1.6.1' // for android
    annotationProcessor 'io.requery:requery-processor:1.6.1'
}

For information on gradle and annotation processing & gradle see the wiki.

License

Copyright (C) 2019 requery.io

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

requery's People

Contributors

0xnm avatar agraphie avatar alex-shpak avatar bazted avatar cbruegg avatar cheese-stands-alone avatar consp1racy avatar debop avatar dennishartrampf avatar dukeyin avatar ema987 avatar entigo avatar fanchao-alphero avatar francoispluchino avatar gaemi avatar grennis avatar jakekdodd avatar krissrex avatar langerhans avatar magister avatar mikenicholls avatar mirkoluchi avatar npurushe avatar nxtstep avatar pluscubed avatar re-thc avatar sakuna63 avatar vjames19 avatar watercrossing avatar yoshiaki-harada avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

requery's Issues

Couple of databases

I have defined a couple of entities and some of them need to go to general db and others to specific db. Is there a way to do this? I want to have exchange specific databases in runtime.

Update i found @entity(model = "general") and @entity(model = "spectific") but when i build the project i get this
Error:(4, 68) error: cannot find symbol class Models and
Error:Attempt to recreate a file for type requery.general.Models

this is general helper

`public class GeneralReQuery {

    private static final String GENERAL = "General";
    private SingleEntityStore<Persistable> generalDataStore;

    /**
     * @return {@link EntityDataStore} single instance for the application. <p/> Note if you're
     * using Dagger you can make this part of your application level module returning {@code
     * @Provides @Singleton}.
     */
    SingleEntityStore<Persistable> getGeneralDataStore(Context context) {
        if (generalDataStore == null) {
            // override onUpgrade to handle migrating to a new version
            DatabaseSource source = new DatabaseSource(context, Models.GENERALDB, GENERAL, 1);
            Configuration configuration = source.getConfiguration();
            generalDataStore = RxSupport.toReactiveStore(new EntityDataStore<>(configuration));
        }
        return generalDataStore;
    }
}`

and specific helper

public class SpecificReQuery {
    private static final String SPECIFIC = "CD";
    private SingleEntityStore<Persistable> specificDataStore;

    /**
     * @return {@link EntityDataStore} single instance for the application. <p/> Note if you're
     * using Dagger you can make this part of your application level module returning {@code
     * @Provides @Singleton}.
     */
    SingleEntityStore<Persistable> getTenantDataStore(Context context, String userid) {
        if (specificDataStore == null) {
            // override onUpgrade to handle migrating to a new version
            DatabaseSource source = new DatabaseSource(context, Models.SPECIFICDB, SPECIFIC + tenantID, 1);
            Configuration configuration = source.getConfiguration();
            specificDataStore = RxSupport.toReactiveStore(
                    new EntityDataStore<Persistable>(configuration));
        }
        return specificDataStore;
    }
}

and these are entities

@Entity(model = "SPECIFICDB")
public interface User {

    @Key
    @Generated
    int getId();

    String getName();

    void setName(String line2);
}
@Entity(model = "GENERALDB")
public interface General {

    @Key
    @Generated
    int getId();

    String getName();

    void setName(String line2);

}

Exceptions should be more informative.

During testing I got the following exception:

java.lang.IllegalStateException
at io.requery.sql.QueryGenerator.appendInsert(QueryGenerator.java:155)
at io.requery.sql.QueryGenerator.toSql(QueryGenerator.java:92)
at io.requery.sql.UpdateOperation$1.get(UpdateOperation.java:53)
at io.requery.sql.UpdateOperation$1.get(UpdateOperation.java:48)
at io.requery.query.SuppliedScalar.value(SuppliedScalar.java:51)
at io.requery.sql.EntityWriter.insert(EntityWriter.java:346)
at io.requery.sql.EntityDataStore.insert(EntityDataStore.java:183)
at com.ubervet.RequeryTest.testUser(RequeryTest.java:47)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:191)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:176)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:555)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1879).

My Entity Class is:

@Entity
public abstract class AbstractUser {
    @Key @Generated
    int localId;
}

I'm testing the library like this:

public class RequeryTest extends ApplicationTestCase<UbervetApplication> {

    SingleEntityStore<Persistable> data;

    public RequeryTest() {
        super(UbervetApplication.class);
    }

    @Override
    protected void setUp() throws Exception {
        super.setUp();

        DatabaseSource source = new DatabaseSource(getContext(), Models.DEFAULT, 1);
        Configuration configuration = source.getConfiguration();
        data = RxSupport.toReactiveStore(new EntityDataStore<Persistable>(configuration));
    }

    @SmallTest
    public void testUser() {
        User user1 = new User();
        User user2 = new User();
        User user3 = new User();

        int localId1 = data.toBlocking().insert(user1).getLocalId();
        int localId2 = data.toBlocking().insert(user2).getLocalId();
        int localId3 = data.toBlocking().insert(user3).getLocalId();

        assertEquals(user1.getLocalId(), localId1);
        assertEquals(user2.getLocalId(), localId2);
        assertEquals(user3.getLocalId(), localId3);
    }
}

I'm sorry if this is trivial to solve but I can't find what is the problem with my code.
Regards

Insert or Update

Hey,

is there a built-in insert or update functionality that I missed? If there does not exist one yet what would you propose as a good workaround?

For now, I have implemented the following specialised extension function in Kotlin (corresponding Java code should be hopefully clear).

fun <E: Persistable> SingleEntityStore<Persistable>.upsert(entity: E): Single<E> {
    return insert(entity).toObservable().onErrorResumeNext { update(entity).toObservable() }.toSingle()
}

It seems to work Not really, I just noticed. Need to improve it.

I tried to create a more generic version.

fun <T, R, E : T> EntityStore<T, R>.upsert(entity: E): R {
    try {
        return insert(entity)
    } catch (e: PersistenceException) {
        return update(entity)
    }
}

Of course, this won't work as the insert/update operations are executed at a later point in time.

In any case, I'd vote for a native upsert implementation ;).

Gson annotations

I notice that generated class files doesn't support annotations like @SerializableName from Gson. Support the annotations might be good to reuse classes for API requests or for validations and something like that.

Do you think that this matches with the goal of the project? I've forked the project and will take a look if I can provide support for this kind of annotation in generated fields, I don't know if this can be possible with the EntityProxy.

BTW, amazing project! I worked with JPA for 7 years and never found something so completed in android like this.

Only works with java8?

This library only works with java8?

If yes, what i need change on android studio to make it works?

Thanks.

name change ?

since the library is pretty new (and pretty awesome!), it would be nice, before it's too late, to consider renaming it to something more abstract.
cause the problem is, it's a real word, which makes google searches less practical.
the "cupboard" library has the same issue ;-)

Entities beginning with letter "m"

I'm having trouble setting up my entity-classes which begin with a 'm':

@Entity
abstract class AbstractManufacture {
    @Key
    @Generated
    int id;

    @OneToMany(mappedBy = "manufacture")
    Set<Product> products;
}
@Entity
abstract class AbstractProduct {
    @Key
    @Generated
    int id;

    @ManyToOne
    Manufacture manufacture;
}

Compiling fails with error: "cannot find symbol variable MANUFACTURE" in the generated class "Manufacture".
I looked into the generated class "Product" which seems to have problems generating setters and getters for "Manufacture", the 'm' is missing:

public static final Attribute<Product, Manufacture> ANUFACTURE = 
    new AttributeBuilder<Product, Manufacture>("manufacture", Manufacture.class)
   ....

and

    public Manufacture getAnufacture() {
        return $proxy.get(ANUFACTURE);
    }

    public void setAnufacture(Manufacture anufacture) {
        $proxy.set(ANUFACTURE, anufacture);
    }

Multiple many to many relations

Does this library support multiple many to many relations?

i have

@Entity
public interface Group {

    @Key
    @Generated
    int getId();

    String getName();

    void setName(String name);

    @JunctionTable(name = "group_members")
    @ManyToMany(mappedBy = "memberGroups")
    Result<User> getMembers();

    @JunctionTable(name = "group_admins")
    @ManyToMany(mappedBy = "adminGroups")
    Result<User> getAdmins();

}

and

@Entity
public interface User {

    @Key
    @Generated
    int getId();

    String getName();

    void setName(String name);

    @ManyToMany(mappedBy = "members")
    Result<Group> getMemberGroups();

    @ManyToMany(mappedBy = "admins")
    Result<Group> getAdminGroups();

}

and i get error when trying to compile

Error:Attempt to recreate a file for type requerytest.AbstractGroupEntity_UserEntity
Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.
Information:BUILD FAILED
Information:Total time: 3.308 secs
Information:2 errors

OneToOne always inserts instead of updates

Hi,

I just played around with the library. I created a simple User and a Phone model, whereas a User always has a phone number. The code is as follows:

@Entity public interface UserDatabaseEntity extends Persistable {

  @Key int getId();

  String getUsername();

  String getEmail();

  @ForeignKey @OneToOne PhoneDatabaseEntity getPhone();
}
@Entity public interface PhoneDatabaseEntity extends Persistable {

  @Key int getId();

  String getNumber();

  @OneToOne(mappedBy = "phone") UserDatabaseEntity getUser();
}
private void storeUser() {
    UserDatabaseEntityEntity user = new UserDatabaseEntityEntity();
    user.setId(0);
    user.setEmail("fghjklร–");
    user.setUsername("fghbjnkl");

    PhoneDatabaseEntityEntity phone = new PhoneDatabaseEntityEntity();
    phone.setId(0);
    phone.setNumber("1234567890");

    user.getAddresses().add(address1);
    user.getAddresses().add(address2);
    user.setPhone(phone);

    if (store.select(UserDatabaseEntity.class).where(UserDatabaseEntityEntity.ID.eq(user.getId())).get().firstOrNull()
        == null) {
      Log.d("TAG", "No user found -> inserting");
      store.insert(user);
    } else {
      Log.d("TAG", "Found user with id -> updating");
      store.update(user);
    }
  }

When I and the code once all gets inserted into the database as expected. After that I get the following exception. It says that it cannot create another phone entity, since there is already one with the given id. Note that I want to set the ids myself and do not want to use auto generated ids. There is a reason for that. Also it seems that the phone is inserted even when I update the user. Shouldn't it update the phone too instead of inserting? Maybe I am doing something wrong?

EDIT: This does not happen when using one to many relationships.

Best regards
dasheck

03-09 10:27:38.924 27648-27648/com.requerytest E/SQLiteLog: (1555) abort at 9 in [insert into PhoneDatabaseEntity (id, number) values (?, ?)]: UNIQUE constraint failed: PhoneDatabaseEntity.id
03-09 10:27:38.928 27648-27648/com.requerytest E/AndroidRuntime: FATAL EXCEPTION: main
                                                                        Process: com.requerytest, PID: 27648
                                                                        java.lang.RuntimeException: Unable to start activity ComponentInfo{com.requerytest/com.requerytest.MainActivity}: io.requery.PersistenceException: java.sql.SQLIntegrityConstraintViolationException: android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: PhoneDatabaseEntity.id (code 1555)
                                                                            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
                                                                            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
                                                                            at android.app.ActivityThread.access$800(ActivityThread.java:151)
                                                                            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
                                                                            at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                            at android.os.Looper.loop(Looper.java:135)
                                                                            at android.app.ActivityThread.main(ActivityThread.java:5254)
                                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                                            at java.lang.reflect.Method.invoke(Method.java:372)
                                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
                                                                         Caused by: io.requery.PersistenceException: java.sql.SQLIntegrityConstraintViolationException: android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: PhoneDatabaseEntity.id (code 1555)
                                                                            at io.requery.sql.UpdateOperation$1.get(UpdateOperation.java:76)
                                                                            at io.requery.sql.UpdateOperation$1.get(UpdateOperation.java:49)
                                                                            at io.requery.query.SuppliedScalar.value(SuppliedScalar.java:51)
                                                                            at io.requery.sql.EntityWriter.insert(EntityWriter.java:422)
                                                                            at io.requery.sql.EntityWriter.cascadeInsert(EntityWriter.java:737)
                                                                            at io.requery.sql.EntityWriter.update(EntityWriter.java:465)
                                                                            at io.requery.sql.EntityDataStore.update(EntityDataStore.java:216)
                                                                            at com.requerytest.MainActivity.storeUser(MainActivity.java:57)
                                                                            at com.requerytest.MainActivity.onCreate(MainActivity.java:25)
                                                                            at android.app.Activity.performCreate(Activity.java:5990)
                                                                            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
                                                                            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
                                                                            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)ย 
                                                                            at android.app.ActivityThread.access$800(ActivityThread.java:151)ย 
                                                                            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)ย 
                                                                            at android.os.Handler.dispatchMessage(Handler.java:102)ย 
                                                                            at android.os.Looper.loop(Looper.java:135)ย 
                                                                            at android.app.ActivityThread.main(ActivityThread.java:5254)ย 
                                                                            at java.lang.reflect.Method.invoke(Native Method)ย 
                                                                            at java.lang.reflect.Method.invoke(Method.java:372)ย 
                                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)ย 
                                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)ย 
                                                                         Caused by: java.sql.SQLIntegrityConstraintViolationException: android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: PhoneDatabaseEntity.id (code 1555)
                                                                            at io.requery.android.sqlite.DatabaseConnection.throwSQLException(DatabaseConnection.java:77)
                                                                            at io.requery.android.sqlite.PreparedStatementAdapter.executeUpdate(PreparedStatementAdapter.java:208)
                                                                            at io.requery.sql.UpdateOperation$1.get(UpdateOperation.java:70)
                                                                            at io.requery.sql.UpdateOperation$1.get(UpdateOperation.java:49)ย 
                                                                            at io.requery.query.SuppliedScalar.value(SuppliedScalar.java:51)ย 
                                                                            at io.requery.sql.EntityWriter.insert(EntityWriter.java:422)ย 
                                                                            at io.requery.sql.EntityWriter.cascadeInsert(EntityWriter.java:737)ย 
                                                                            at io.requery.sql.EntityWriter.update(EntityWriter.java:465)ย 
                                                                            at io.requery.sql.EntityDataStore.update(EntityDataStore.java:216)ย 
                                                                            at com.requerytest.MainActivity.storeUser(MainActivity.java:57)ย 
                                                                            at com.requerytest.MainActivity.onCreate(MainActivity.java:25)ย 
                                                                            at android.app.Activity.performCreate(Activity.java:5990)ย 
                                                                            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)ย 
                                                                            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)ย 
                                                                            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)ย 
                                                                            at android.app.ActivityThread.access$800(ActivityThread.java:151)ย 
                                                                            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)ย 
                                                                            at android.os.Handler.dispatchMessage(Handler.java:102)ย 
                                                                            at android.os.Looper.loop(Looper.java:135)ย 
                                                                            at android.app.ActivityThread.main(ActivityThread.java:5254)ย 
                                                                            at java.lang.reflect.Method.invoke(Native Method)ย 
                                                                            at java.lang.reflect.Method.invoke(Method.java:372)ย 
                                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)ย 
                                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)ย 
                                                                         Caused by: android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: PhoneDatabaseEntity.id (code 1555)
                                                                            at android.database.sqlite.SQLiteConnection.nativeExecuteForChangedRowCount(Native Method)
                                                                            at android.database.sqlite.SQLiteConnection.executeForChangedRowCount(SQLiteConnection.java:734)
                                                                            at android.database.sqlite.SQLiteSession.executeForChangedRowCount(SQLiteSession.java:754)
                                                                            at android.database.sqlite.SQLiteStatement.executeUpdateDelete(SQLiteStatement.java:64)
                                                                            at io.requery.android.sqlite.PreparedStatementAdapter.executeUpdate(PreparedStatementAdapter.java:206)
                                                                            at io.requery.sql.UpdateOperation$1.get(UpdateOperation.java:70)ย 
                                                                            at io.requery.sql.UpdateOperation$1.get(UpdateOperation.java:49)ย 
                                                                            at io.requery.query.SuppliedScalar.value(SuppliedScalar.java:51)ย 
                                                                            at io.requery.sql.EntityWriter.insert(EntityWriter.java:422)ย 
                                                                            at io.requery.sql.EntityWriter.cascadeInsert(EntityWriter.java:737)ย 
                                                                            at io.requery.sql.EntityWriter.update(EntityWriter.java:465)ย 
                                                                            at io.requery.sql.EntityDataStore.update(EntityDataStore.java:216)ย 
                                                                            at com.requerytest.MainActivity.storeUser(MainActivity.java:57)ย 
                                                                            at com.requerytest.MainActivity.onCreate(MainActivity.java:25)ย 
                                                                            at android.app.Activity.performCreate(Activity.java:5990)ย 
                                                                            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)ย 
                                                                            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)ย 
                                                                            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)ย 
                                                                            at android.app.ActivityThread.access$800(ActivityThread.java:151)ย 
                                                                            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)ย 
                                                                            at android.os.Handler.dispatchMessage(Handler.java:102)ย 
                                                                            at android.os.Looper.loop(Looper.java:135)ย 
                                                                            at android.app.ActivityThread.main(ActivityThread.java:5254)ย 
                                                                            at java.lang.reflect.Method.invoke(Native Method)ย 
                                                                            at java.lang.reflect.Method.invoke(Method.java:372)ย 
                                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)ย 
                                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)ย 

Performance issue

Is there a way to see what exact sql statements are generated by the library?

We have 10 tables in db with lots of relations between them (One to many, many to many, one to one) and we get a deep nested json mapped to response object from server that needs to be inserted in at least 8 tables, we check every element by selecting and depending on if it exists doing insert or update.
For a response of 100 json objects (about 56kb) on xperia e it takes about 9 seconds to insert them with lots of gcforaloc calls, galaxy s4 takes about 2.3 seconds.

Could you give an example for a rule of thumb how this should be done?

Question about delete operation

Hi!
I move my project from activeandroid to requery and have some question.
For example, how can I do opeartion with blocking thread.
MyApplication.getInstance().getData().toBlocking().*?

Why this code not working?

MyApplication.getInstance().getData().toBlocking().delete(City.class).get();
List<City> wasCities=MyApplication.getInstance().getData().select(City.class).get().toList();
MyApplication.getInstance().getData().toBlocking().insert(cities);

wasCities contains items after deletion.

ManyToMany problem

Hi! There is some problem. If I link product to section(ManyToMany) first time, it is working, second time not working.
I have two classes:
AbstractSection

@Entity
@JsonDeserialize(as=Section.class)
@JsonIgnoreProperties(ignoreUnknown = true)
public abstract class AbstractSection implements Persistable
{
    @Key
    public int id;
    public String name;

    @JunctionTable(name = "section_products")
    @ManyToMany(cascade = {CascadeAction.DELETE, CascadeAction.SAVE})
    public List<Product> products;
}

and AbstractProduct

@Entity
@JsonDeserialize(as=Product.class)
@JsonIgnoreProperties(ignoreUnknown = true)
public abstract class AbstractProduct
{
    @Key
    public int id;
    public String name;
    public String description;

    @Transient
    public int section_id[];

    @ManyToMany
    public List<Section> sections;
}

This code saves and connect products to section

//removing prev products
MyApplication.getInstance().getData().toBlocking().delete(Product.class).get().value();
List<Product> position=....//parsed from network
final int size=position.size();
            for(int i=0;i<size;++i) {
                Product product=position.get(i);
                MyApplication.getInstance().getData().toBlocking().insert(product);
                if(product.section_id!=null&&product.section_id.length!=0)
                {
                    for (int sectionId : product.section_id)
                    {
                        Section section=MyApplication.getInstance().getData().toBlocking().select(Section.class).where(Section.ID.equal(sectionId)).get().firstOrNull();
                        section.getProducts().add(product);
                        product.getSections().add(section);
                        MyApplication.getInstance().getData().toBlocking().refresh(section);
                        MyApplication.getInstance().getData().toBlocking().refresh(product);
                    }
                }
            }

After using this function second time method section.getProducts() return empty list but first time using above code function section.getProducts() returns normal list.
Do I have some problems in code or inside requery?

Data removed after cold start app

I have sections and items in it. When I load and save data it works ok, but after restart app(remove from memory by swiping) and start app my data disappear.
I use two ManyToMany annotations(maybe it is important to fix problem). I use requery 1.0.0-beta2.

Make generated classes "friend" classes instead of extending entity class

What if the generated code used some kind of mapping to persist our entity instead of putting all the information needed in a class that extends it.

I'm suggesting this because I was trying to make this library (which is good as it is right now, btw) to work together with LoganSquare, the code generated JSON serialization library. The problem arises because you can't serialize a generated entity class as it is not annotated. I don't know if this would be hard to implement or this isn't the purpose of this lib. Maybe add this as an optional way.

Sorry if I wasn't clear enough, English isn't my native language.
Thank you

Constraint exception when inserting

I am trying to write a performance test for your library, but currently fail to insert elements due to constraint exceptions. I feel like I do not understand correctly how to insert/update existing entity objects.

The code affected is in greenrobot/android-database-performance#7.

The entities are generated like:

protected static SimpleEntityNotNull createEntity(long id) {
        SimpleEntityNotNull entity = new SimpleEntityNotNull();
        entity.setId(id);
        entity.setSimpleBoolean(true);
        entity.setSimpleByte(Byte.MAX_VALUE);
        entity.setSimpleShort(Short.MAX_VALUE);
        entity.setSimpleInt(Integer.MAX_VALUE);
        entity.setSimpleLong(Long.MAX_VALUE);
        entity.setSimpleFloat(Float.MAX_VALUE);
        entity.setSimpleDouble(Double.MAX_VALUE);
        entity.setSimpleString("greenrobot greenDAO");
        byte[] bytes = { 42, -17, 23, 0, 127, -128 };
        entity.setSimpleByteArray(bytes);
        return entity;
    }

Then they are inserted like

DatabaseSource source = new DatabaseSource(getApplication(), Models.DEFAULT, DATABASE_VERSION);
Configuration configuration = new ConfigurationBuilder(source, Models.DEFAULT).build();
BlockingEntityStore<Object> data = new EntityDataStore<>(configuration).toBlocking();

// TODO: NOT NULL constraint failed: SimpleEntityNotNull.simpleByte
data.insert(entities.get(i)); // entites = List<SimpleEntityNotNull>

I saw that in other issues (#32, #33) inserting entities was done pretty much the same. As the documentation is spotty in that regard I hope you can point me into the right direction.

Cannot find symbol method toInstant()

Hey,

I've cloned this repository and was trying to run the example project via Android Studio. However, I received the following error message: cannot find symbol method toInstant(). Here's a screenshot of the compilation errors.
screen shot 2016-02-19 at 09 36 58

Do you have any pointers about how to solve this problem?

OneToMany and ManyToOne

Hey there,
Thirst of all thank you for this very nice library ๐Ÿ‘

Yet I am currently having an issues with implementing a OneToManyand ManyToOnerelationship as follows:

@Entity()
public interface Category {

    // Getters

    @Key
    @Generated
    int getId();

    @OneToMany(mappedBy = "category")
    Set<Record> getRecords();
}

@Entity
public interface Record {

    // Getters

    @Key
    @Generated
    int getId();

    @ManyToOne()
    Category getCategory();
}

At first it seems to work, but when I restart the application via Android Studio (and only then) the app crashes with the following stacktrace:

FATAL EXCEPTION: java.lang.IllegalStateException                                                                                                                                                 
at io.requery.sql.EntityReader.associativeQuery(EntityReader.java:304)
at io.requery.sql.EntityReader.refreshAssociation(EntityReader.java:227)
at io.requery.sql.EntityReader.refresh(EntityReader.java:219)
at io.requery.sql.EntityReader.refresh(EntityReader.java:153)
at io.requery.sql.EntityReader.load(EntityReader.java:123)
at io.requery.proxy.EntityProxy.get(EntityProxy.java:96)
at  o.requery.proxy.EntityProxy.get(EntityProxy.java:80)
at xxx.models.RecordEntity.getCategory(RecordEntity.java:184)

Following the stacktrace leads to https://github.com/requery/requery/blob/master/requery/src/main/java/io/requery/sql/EntityReader.java#L304. Where I obtain the following code snippet:

 case MANY_TO_ONE:
 default:
     throw new IllegalStateException();

My question now is:
Am I doing something completely wrong or have a basic misunderstanding here?
Or is this feature yet to be implemented?
Or is it even a bug?

Thanks in advance.

Is latest build broken?

Hi, I am trying this library and when I add all the dependencies and refresh gradle project only requery android is available, is the build broken or is the problem somewhere in my app?

Thanks

Issue with entity mapping

Hi i have

@Entity
public interface State {

    @Key
    @Generated
    int getId();

    String getPostCode();

    void setPostCode(String line1);

    String getName();

    void setName(String line2);

    @OneToMany(mappedBy = "state")
    Result<City> getCities();
}
@Entity
public interface City {

    @Key
    @Generated
    int getId();

    String getPTT();

    void setPTT(String ptt);

    String getName();

    void setName(String name);

    @ManyToOne
    State getState();

    void setState(State state);

    @OneToMany(mappedBy = "city")
    Result<Street> getStreets();
}

and

@Entity
public interface Street {

    @Key
    @Generated
    int getId();

    String getName();

    void setName(String name);

    @ManyToOne
    City getCity();

    void setCity(City city);
}

When i try to compile it just give errors like this

Error:(26, 11) Note: mapping: requerytest.CityEntity.state -> requerytest.StateEntity.cities
Error:(31, 20) Note: mapping: requerytest.CityEntity.streets -> requerytest.StreetEntity.city
Note: mapping: requerytest.StreetEntity.city -> requerytest.CityEntity.streets
Note: mapping: requerytest.StateEntity.cities -> requerytest.CityEntity.state
Note: mapping: requerytest.CityEntity.state -> requerytest.StateEntity.cities
Note: mapping: requerytest.CityEntity.streets -> requerytest.StreetEntity.city
Note: mapping: requerytest.StreetEntity.city -> requerytest.CityEntity.streets
Note: mapping: requerytest.StateEntity.cities -> requerytest.CityEntity.state
Note: mapping: requerytest.CityEntity.state -> requerytest.StateEntity.cities
Note: mapping: requerytest.CityEntity.streets -> .requerytest.StreetEntity.city

I can't make out anything from these errors. Am i doing something wrong?

Multi database compile issues

helper

public class CityReQuery {

    public static final String STATE_DB = "state_db";

    private static CityReQuery mInstance;
    private SingleEntityStore<Persistable> entityStore;

    private CityReQuery() {
    }

    public static CityReQuery getInstance() {
        if (mInstance == null) {
            mInstance = new CityReQuery();
        }
        return mInstance;
    }

    public SingleEntityStore<Persistable> getEntityStore() {
        return entityStore;
    }

    /**
     * Initialize general database on first start
     */
    public void init(Context context) {
        initGeneralDataStore(context);
    }

    /**
     * @return {@link EntityDataStore} single instance for the application. <p/> Note if you're
     * using Dagger you can make this part of your application level module returning {@code
     * @Provides @Singleton}.
     */
    private SingleEntityStore<Persistable> initGeneralDataStore(Context context) {
        if (entityStore == null) {
            // override onUpgrade to handle migrating to a new version
//            DatabaseSource source = new DatabaseSource(context, , Models., STATE_DB, 1);
//            Configuration configuration = source.getConfiguration();
//            entityStore = RxSupport.toReactiveStore(new EntityDataStore<>(configuration));
        }
        return entityStore;
    }
}

helper,

public class UserReQuery {

    public static final String USER_DB = "user_db";

    private static UserReQuery mInstance;
    private SingleEntityStore<Persistable> entityStore;

    private UserReQuery() {
    }

    public static UserReQuery getInstance() {
        if (mInstance == null) {
            mInstance = new UserReQuery();
        }
        return mInstance;
    }

    public SingleEntityStore<Persistable> getEntityStore() {
        return entityStore;
    }

    /**
     * Initialize general database on first start
     */
    public void init(Context context) {
        initGeneralDataStore(context);
    }

    /**
     * @return {@link EntityDataStore} single instance for the application. <p/> Note if you're
     * using Dagger you can make this part of your application level module returning {@code
     * @Provides @Singleton}.
     */
    private SingleEntityStore<Persistable> initGeneralDataStore(Context context) {
        if (entityStore == null) {
            // override onUpgrade to handle migrating to a new version
//            DatabaseSource source = new DatabaseSource(context, Models., USER_DB, 1);
//            Configuration configuration = source.getConfiguration();
//            entityStore = RxSupport.toReactiveStore(new EntityDataStore<>(configuration));
        }
        return entityStore;
    }
}

user


@Entity(name = UserReQuery.USER_DB)
public interface User {

    @Key
    @Generated
    int getId();

    String getName();

    void setName(String name);

    @ManyToMany(mappedBy = "members")
    Result<Group> getMemberGroups();

    @ManyToMany(mappedBy = "admins")
    Result<Group> getAdminGroups();

}

group

@Entity(name = UserReQuery.USER_DB)
public interface Group {

    @Key
    @Generated
    int getId();

    String getName();

    void setName(String name);

    @JunctionTable(name = "group_members")
    @ManyToMany(mappedBy = "memberGroups")
    Result<User> getMembers();

    @JunctionTable(name = "group_admins")
    @ManyToMany(mappedBy = "adminGroups")
    Result<User> getAdmins();
}

city

@Entity(name = CityReQuery.STATE_DB)
public interface City {

    @Key
    @Generated
    int getId();

    String getPTT();

    void setPTT(String ptt);

    String getName();

    void setName(String name);

    @ManyToOne
    State getState();

    void setState(State state);

    @OneToMany(mappedBy = "city")
    Result<Street> getStreets();
}

state

@Entity(name = CityReQuery.STATE_DB)
public interface State {

    @Key
    @Generated
    int getId();

    String getPostCode();

    void setPostCode(String line1);

    String getName();

    void setName(String line2);

    @OneToMany(mappedBy = "state")
    Result<City> getCities();
}

street

@Entity(name = CityReQuery.STATE_DB)
public interface Street {

    @Key
    @Generated
    int getId();

    String getName();

    void setName(String name);

    @ManyToOne
    City getCity();

    void setCity(City city);

}

and when i try to compile it throws this stack trace

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:compileDebugJavaWithJavac'.
> java.lang.IllegalArgumentException: couldn't make a guess for requerytest.user_db

* Try:
Run with --info or --debug option to get more log output.

* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:compileDebugJavaWithJavac'.
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:69)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:46)
        at org.gradle.api.internal.tasks.execution.PostExecutionAnalysisTaskExecuter.execute(PostExecutionAnalysisTaskExecuter.java:35)
        at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:64)
        at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
        at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:52)
        at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
        at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:53)
        at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:203)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:185)
        at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.processTask(AbstractTaskPlanExecutor.java:66)
        at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.run(AbstractTaskPlanExecutor.java:50)
        at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:54)
        at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:40)
Caused by: java.lang.RuntimeException: java.lang.IllegalArgumentException: couldn't make a guess for requerytest.user_db
        at com.sun.tools.javac.main.Main.compile(Main.java:553)
        at com.sun.tools.javac.api.JavacTaskImpl.doCall(JavacTaskImpl.java:129)
        at com.sun.tools.javac.api.JavacTaskImpl.call(JavacTaskImpl.java:138)
        at org.gradle.api.internal.tasks.compile.JdkJavaCompiler.execute(JdkJavaCompiler.java:45)
        at org.gradle.api.internal.tasks.compile.JdkJavaCompiler.execute(JdkJavaCompiler.java:33)
        at org.gradle.api.internal.tasks.compile.NormalizingJavaCompiler.delegateAndHandleErrors(NormalizingJavaCompiler.java:101)
        at org.gradle.api.internal.tasks.compile.NormalizingJavaCompiler.execute(NormalizingJavaCompiler.java:50)
        at org.gradle.api.internal.tasks.compile.NormalizingJavaCompiler.execute(NormalizingJavaCompiler.java:36)
        at org.gradle.api.internal.tasks.compile.CleaningJavaCompilerSupport.execute(CleaningJavaCompilerSupport.java:34)
        at org.gradle.api.internal.tasks.compile.CleaningJavaCompilerSupport.execute(CleaningJavaCompilerSupport.java:25)
        at org.gradle.api.tasks.compile.JavaCompile.performCompilation(JavaCompile.java:157)
        at org.gradle.api.tasks.compile.JavaCompile.compile(JavaCompile.java:139)
        at org.gradle.api.tasks.compile.JavaCompile.compile(JavaCompile.java:93)
        at com.android.build.gradle.tasks.factory.AndroidJavaCompile.compile(AndroidJavaCompile.java:39)
        at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:75)
        at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$IncrementalTaskAction.doExecute(AnnotationProcessingTaskFactory.java:244)
        at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:220)
        at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$IncrementalTaskAction.execute(AnnotationProcessingTaskFactory.java:231)
        at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:209)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:80)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:61)
        ... 14 more
Caused by: java.lang.IllegalArgumentException: couldn't make a guess for requerytest.user_db
        at com.squareup.javapoet.Util.checkArgument(Util.java:62)
        at com.squareup.javapoet.ClassName.bestGuess(ClassName.java:149)
        at io.requery.processor.EntityNameResolver.typeNameOf(EntityNameResolver.java:35)
        at io.requery.processor.EntityGenerator.<init>(EntityGenerator.java:108)
        at io.requery.processor.EntityProcessor.process(EntityProcessor.java:114)
        at com.sun.tools.javac.processing.JavacProcessingEnvironment.callProcessor(JavacProcessingEnvironment.java:794)
        at com.sun.tools.javac.processing.JavacProcessingEnvironment.discoverAndRunProcs(JavacProcessingEnvironment.java:705)
        at com.sun.tools.javac.processing.JavacProcessingEnvironment.access$1800(JavacProcessingEnvironment.java:91)
        at com.sun.tools.javac.processing.JavacProcessingEnvironment$Round.run(JavacProcessingEnvironment.java:1035)
        at com.sun.tools.javac.processing.JavacProcessingEnvironment.doProcessing(JavacProcessingEnvironment.java:1176)
        at com.sun.tools.javac.main.JavaCompiler.processAnnotations(JavaCompiler.java:1170)
        at com.sun.tools.javac.main.JavaCompiler.compile(JavaCompiler.java:856)
        at com.sun.tools.javac.main.Main.compile(Main.java:523)
        ... 34 more


Table joins

How do joins work in requery? Let's say my schema has 3 entities: Sailor(id), Boat(id, color), Reservation(sid, bid, date). Is there a way to get all Sailors who reserved a red Boat?
I see that requery has a Join interface, but I couldn't find a way to join tables on foreign keys.

Clarify Usage of QueryRecyclerAdapter

Hi, I am having trouble getting my extended QueryRecyclerAdapter to populate a recyclerview. There are no errors thrown, but it's simply not happening.

I have overridden performQuery, onCreateViewHolder, and onBindViewHolder. I am also calling queryAsync after setting up an executor and adding the adapter to the recyclerView. Any help you can provide on this matter would be appreciated.

Duplicate id Rows

While inspecting the generated database I noticed that there are two id rows for every table with the same content. For example, if I have the following class.

@Entity
public abstract class AbstractUser {
    @Key
    long id;
    String name;
    String profilePicUrl;
}

Then the resulting table has the following rows.

 id | id | name | profilePicUrl
--------------------------------
 1    1    Alex   http://
 2    2    Tobi   http://...

ManyToMany: "compound-entity" not generated and setters not generated in entities

I can't seem to get ManyToMany relationships to work:

@Entity
public interface User extends Parcelable {

    @Key
    @Generated
    int getId();


    @ManyToMany(mappedBy = "owners", cascade = CascadeAction.NONE)
    List<Account> getOwned();
    //void setOwned(List<Account> accounts);
}
@Entity
public interface Account extends Parcelable {

    @Key
    @Generated
    int getId();

    @ManyToMany(mappedBy = "owners", cascade = CascadeAction.NONE)
    List<User> getOwners();

}

Gradle always says: error: cannot find symbol class AccountEntity_UserEntity
The class "AccountEntity_UserEntity" is not generated, should we create this ourselves?

Another issue, setters for ManyToMany and OneToMany are not created (if I uncomment the setter-line above, it always says "xEntity is always abstract and does not override ...blabla", the setter is not generated).

Limit

Do you plan to support raw sql?

I want to select rows from - to, limit method only receives one value.

Subqueries

Hi, I am currently trying to build a select-statement with a subquery but I cannot find any methods for that. Is that not possible? If not, is there an option for using raw queries? This wouldn't be a perfect solution but it could bypass my problem right now.

Build fails when using retrolambda

I've tried to enable Lambda expressions in Android example project:

apply plugin: 'me.tatarka.retrolambda'

...

compileOptions {
     sourceCompatibility JavaVersion.VERSION_1_8
     targetCompatibility JavaVersion.VERSION_1_8
}

...

When building @entity annotated classes are not visible and builds fail.

Is it possible to run Requery alongside with Retrolambda?

I considered porting my current project from Squidb to Requery, but I use there a lot of lambda expressions.

[Databinding] Generated classes cannot be used in xml

I've modified the example Android code to use generated classes in xml as following:

<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
     <variable name="person" type="io.requery.android.example.app.model.PersonEntity"/>
</data>
...

Then builds fails during ":requery-android:example:compileDebugJavaWithJavac" with


Execution failed for task ':requery-android:example:compileDebugJavaWithJavac'.
> java.lang.RuntimeException: Found data binding errors.
  ****/ data binding error ****msg:Cannot resolve type for person~ file:/Users/krzysztofwrobel/MyPrograms/Playground/requery/requery-android/example/src/main/res/layout/activity_edit_person.xml loc:20:30 - 20:35 ****\ data binding error ****

I'm planning to move my project to Requery so I've modified bunch of things in exmaple project and published it here:
https://github.com/KrzysztofWrobel/requery

Anyone know why I can't use generated classes in xml?

Error when reading Long value from database.

Long value gets persisted as INTEGER sql type which is fine, but is mapped as java.lang.Integer when read from database, then an invalid typecast exception is thrown when converting.

Workaround i found is to use a custom converter to a BLOB type:

public class LongToByteArrayConverter implements Converter<Long, byte[]> {

    @Override
    public Class<Long> mappedType() {
        return Long.class;
    }

    @Override
    public Class<byte[]> persistedType() {
        return byte[].class;
    }

    @Override
    public Integer persistedSize() {
        return Long.SIZE / Byte.SIZE;
    }

    @Override
    public byte[] convertToPersisted(Long value) {
        return ByteBuffer.allocate(Long.SIZE / Byte.SIZE).putLong(value).array();
    }

    @Override
    public Long convertToMapped(Class<? extends Long> type, byte[] value) {
        return ByteBuffer.wrap(value).getLong();
    }
}

Maybe a way to know when to convert back to java's Long is needed.

Can't get things working on new project.

I'd love to use your lib for a new personal project, and while I was setting it up, I was never able to get entities generated.

What am I missing ?

Project is absolutely empty, only contains the following models.

Models:

import android.os.Parcelable;

import java.util.Date;

import io.requery.Entity;
import io.requery.Generated;
import io.requery.Index;
import io.requery.Key;
import io.requery.ManyToOne;
import io.requery.Persistable;

@Entity
public interface ITransaction extends Persistable, Parcelable {

    @Key @Generated
    long getId();

    float getValue();

    String getDescription();

    Date getDate();

    @ManyToOne
    Category getCategory(); // Expecting generated, or should I reference interface?

    @ManyToOne
    Account getFromAccount(); // Expecting generated, or should I reference interface?
}
@Entity
public interface IAccount extends Persistable, Parcelable {

    @Key
    String getName();

    float getCapital();
}
@Entity
public interface ICategory extends Persistable, Parcelable {

    @Key
    String getName();
}

Probably usefull info:
$ java -version

java version "1.8.0_74"
Java(TM) SE Runtime Environment (build 1.8.0_74-b02)
Java HotSpot(TM) 64-Bit Server VM (build 25.74-b02, mixed mode)

compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_7
    targetCompatibility JavaVersion.VERSION_1_7
}

apply plugin: 'com.neenbedankt.android-apt'

repositories {
    maven { url 'http://oss.jfrog.org/artifactory/oss-snapshot-local' }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.android.support:design:23.1.1'

    compile 'io.requery:requery:1.0-SNAPSHOT'
    compile 'io.requery:requery-android:1.0-SNAPSHOT'
    apt 'io.requery:requery-processor:1.0-SNAPSHOT'

    compile 'io.reactivex:rxjava:1.1.0'
    compile 'io.reactivex:rxandroid:1.1.0'
    compile 'com.google.dagger:dagger:2.0.2'
    provided 'com.google.dagger:dagger-compiler:2.0.2'
}

Things I tried with no success:

  • $ gradle clean build
  • $ gradle assemble
  • Invalidate caches and restart Android Studio.
  • Clone requery and compile example.

Thanks in advance!

Result.toObservable() which emits result on subscribe and on further updates.

As far as i can see, Result has two toObservable-methods:

  • toObservable: Converts the Result to an Observable which, emits an item of result at a time.
  • toSelfObservable: Emits only, when a commit affects the query.

Enhancement:
It would be nice to have an Observable, which emits once on subscribe and emits on further updates (like in StorIO). With this, the first toObservable wouldn't be needed anymore, since we can simulate it with take(1) and flatmap. The second could be simulated by skip(1).

Embedded objects support

As @Embedded JPA annotation.

I already have table with entity and its "embedded" object fields stored in the same table (I currently use "raw" SQL). Being unable to map requery entities to my table prevents me from migrating to requery. =(

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.