Code Monkey home page Code Monkey logo

ormlite-core's Introduction

ORMLite Core

This package provides the core functionality for the JDBC and Android packages. Users that are connecting to SQL databases via JDBC should download the ormlite-jdbc package instead which includes these core classes. Android users should download the ormlite-android package instead which also includes these core classes.

ORMLite is easy to use and provides the following features:

Enjoy, Gray Watson

Code Example

The following is a quick code example to give you a taste on how to use the library.

// this uses h2 but you can change it to match your database
String databaseUrl = "jdbc:h2:mem:account";
// create a connection source to our database
ConnectionSource connectionSource = new JdbcConnectionSource(databaseUrl);

// instantiate the DAO to handle Account with String id
Dao<Account,String> accountDao = DaoManager.createDao(connectionSource, Account.class);

// if you need to create the 'accounts' table make this call
TableUtils.createTable(connectionSource, Account.class);

// create an instance of Account
String name = "Jim Smith";
Account account = new Account(name, "_secret");

// persist the account object to the database
accountDao.create(account);

// retrieve the account
Account account2 = accountDao.queryForId(name);
// show its password
System.out.println("Account: " + account2.getPassword());

// close the connection source
connectionSource.close();

Logging Information

ORMLite has copied in logging code from SimpleLogging which backends to a number of different logging systems and is configurable via code or configuration. For more details see the logging documentation.

Maven Configuration

For JDBC usage, you should depend on Maven Central which includes the core classes.

<dependency>
	<groupId>com.j256.ormlite</groupId>
	<artifactId>ormlite-jdbc</artifactId>
	<version>6.1</version>
</dependency>

For Android usage, you should depend on Maven Central which includes the core classes.

<dependency>
	<groupId>com.j256.ormlite</groupId>
	<artifactId>ormlite-android</artifactId>
	<version>6.1</version>
</dependency>

ChangeLog Release Notes

See the ChangeLog.txt file.

ormlite-core's People

Contributors

blackbaroness avatar bo98 avatar bosborn avatar charleszkq avatar dependabot[bot] avatar dlew avatar folkyatina avatar funkthemonk avatar fuud avatar graynk avatar j256 avatar jlleitschuh avatar juur avatar marcmil avatar miha-x64 avatar nanaokada avatar noordawod avatar nunoar avatar p91paul avatar svenjacobs avatar tsharp avatar vladad avatar zhemaituk 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

ormlite-core's Issues

RuntimeExceptionDaoTest Fails - Ubuntu Maven 3

Running com.j256.ormlite.dao.RuntimeExceptionDaoTest
2014-09-02 14:20:57,786 [INFO] TableUtils dropping table 'foo'
2014-09-02 14:20:57,786 [INFO] TableUtils ignoring drop error 'org.h2.jdbc.JdbcSQLException: Table "FOO" not found; SQL statement:
DROP TABLE `foo`  [42102-128]' for statement: DROP TABLE `foo` 
2014-09-02 14:20:57,786 [INFO] TableUtils creating table 'foo'
2014-09-02 14:20:57,787 [INFO] TableUtils executed create table statement changed 0 rows: CREATE TABLE `foo` (`id` INTEGER AUTO_INCREMENT , `val` INTEGER , `equal` INTEGER , `string` VARCHAR(255) , PRIMARY KEY (`id`) ) 
2014-09-02 14:20:57,787 [DEBUG] BaseMappedStatement insert data with statement 'INSERT INTO `foo` (`val` ,`equal` ,`string` ) VALUES (?,?,?)' and 3 args, changed 1 rows
2014-09-02 14:20:57,787 [TRACE] BaseMappedStatement insert arguments: [1232131321, 0, null]
2014-09-02 14:20:57,787 [DEBUG] BaseMappedStatement assigned id '1' from keyholder to 'id' in Foo object
2014-09-02 14:20:57,787 [DEBUG] BaseMappedStatement query-for-id using 'SELECT * FROM `foo` WHERE `id` = ?' and 1 args, got 1 result
2014-09-02 14:20:57,787 [TRACE] BaseMappedStatement query-for-id arguments: [1]
2014-09-02 14:20:57,788 [DEBUG] BaseMappedStatement prepared statement 'SELECT * FROM `foo` ' with 0 args
2014-09-02 14:20:57,788 [DEBUG] StatementExecutor query of 'SELECT * FROM `foo` ' returned 1 results
2014-09-02 14:20:57,788 [DEBUG] BaseMappedStatement prepared statement 'SELECT * FROM `foo` ' with 0 args
2014-09-02 14:20:57,788 [DEBUG] BaseMappedStatement prepared statement 'SELECT * FROM `foo` WHERE `id` = 1 ' with 0 args
2014-09-02 14:20:57,788 [DEBUG] StatementExecutor query of 'SELECT * FROM `foo` WHERE `id` = 1 ' returned 1 results
2014-09-02 14:20:57,789 [DEBUG] BaseMappedStatement prepared statement 'SELECT * FROM `foo` WHERE (`id` = 1 AND `val` = 1232131321 ) ' with 0 args
2014-09-02 14:20:57,789 [DEBUG] StatementExecutor query of 'SELECT * FROM `foo` WHERE (`id` = 1 AND `val` = 1232131321 ) ' returned 1 results
2014-09-02 14:20:57,789 [DEBUG] BaseMappedStatement prepared statement 'SELECT * FROM `foo` WHERE (`id` = ? AND `val` = ? ) ' with 2 args
2014-09-02 14:20:57,789 [TRACE] BaseMappedStatement prepared statement arguments: [1, 1232131321]
2014-09-02 14:20:57,789 [DEBUG] StatementExecutor query of 'SELECT * FROM `foo` WHERE (`id` = ? AND `val` = ? ) ' returned 1 results
2014-09-02 14:20:57,789 [DEBUG] BaseMappedStatement query-for-id using 'SELECT * FROM `foo` WHERE `id` = ?' and 1 args, got 1 result
2014-09-02 14:20:57,789 [TRACE] BaseMappedStatement query-for-id arguments: [1]
2014-09-02 14:20:57,789 [DEBUG] BaseMappedStatement query-for-id using 'SELECT * FROM `foo` WHERE `id` = ?' and 1 args, got 1 result
2014-09-02 14:20:57,789 [TRACE] BaseMappedStatement query-for-id arguments: [1]
2014-09-02 14:20:57,790 [DEBUG] BaseMappedStatement update data with statement 'UPDATE `foo` SET `val` = ?, `equal` = ?, `string` = ? WHERE `id` = ?' and 4 args, changed 1 rows
2014-09-02 14:20:57,790 [TRACE] BaseMappedStatement update arguments: [342342343, 0, null, 1]
2014-09-02 14:20:57,790 [DEBUG] BaseMappedStatement refresh using 'SELECT * FROM `foo` WHERE `id` = ?' and 1 args, got 1 result
2014-09-02 14:20:57,790 [TRACE] BaseMappedStatement refresh arguments: [1]
2014-09-02 14:20:57,790 [DEBUG] BaseMappedStatement delete data with statement 'DELETE FROM `foo` WHERE `id` = ?' and 1 args, changed 1 rows
2014-09-02 14:20:57,790 [TRACE] BaseMappedStatement delete arguments: [1]
2014-09-02 14:20:57,790 [DEBUG] BaseMappedStatement query-for-id using 'SELECT * FROM `foo` WHERE `id` = ?' and 1 args, got no results
2014-09-02 14:20:57,790 [TRACE] BaseMappedStatement query-for-id arguments: [1]
2014-09-02 14:20:57,790 [DEBUG] BaseMappedStatement prepared statement 'SELECT * FROM `foo` ' with 0 args
2014-09-02 14:20:57,790 [DEBUG] StatementExecutor query of 'SELECT * FROM `foo` ' returned 0 results
2014-09-02 14:20:57,790 [DEBUG] BaseMappedStatement prepared statement 'SELECT * FROM `foo` ' with 0 args
2014-09-02 14:20:57,791 [INFO] TableUtils dropping table 'foo'
2014-09-02 14:20:57,792 [INFO] TableUtils ignoring drop error 'org.h2.jdbc.JdbcSQLException: Table "FOO" not found; SQL statement:
DROP TABLE `foo`  [42102-128]' for statement: DROP TABLE `foo` 
2014-09-02 14:20:57,792 [INFO] TableUtils creating table 'foo'
2014-09-02 14:20:57,792 [INFO] TableUtils executed create table statement changed 0 rows: CREATE TABLE `foo` (`id` INTEGER AUTO_INCREMENT , `val` INTEGER , `equal` INTEGER , `string` VARCHAR(255) , PRIMARY KEY (`id`) ) 
2014-09-02 14:20:57,792 [DEBUG] BaseMappedStatement insert data with statement 'INSERT INTO `foo` (`val` ,`equal` ,`string` ) VALUES (?,?,?)' and 3 args, changed 1 rows
2014-09-02 14:20:57,792 [TRACE] BaseMappedStatement insert arguments: [1232131321, 0, null]
2014-09-02 14:20:57,792 [DEBUG] BaseMappedStatement assigned id '1' from keyholder to 'id' in Foo object
2014-09-02 14:20:57,793 [DEBUG] BaseMappedStatement prepared statement 'SELECT * FROM `foo` WHERE (`id` = 1 ) ' with 0 args
2014-09-02 14:20:57,793 [DEBUG] StatementExecutor query of 'SELECT * FROM `foo` WHERE (`id` = 1 ) ' returned 1 results
2014-09-02 14:20:57,793 [DEBUG] BaseMappedStatement prepared statement 'SELECT * FROM `foo` WHERE (`id` = ? ) ' with 1 args
2014-09-02 14:20:57,793 [TRACE] BaseMappedStatement prepared statement arguments: [1]
2014-09-02 14:20:57,794 [DEBUG] StatementExecutor query of 'SELECT * FROM `foo` WHERE (`id` = ? ) ' returned 1 results
2014-09-02 14:20:57,794 [DEBUG] BaseMappedStatement prepared statement 'SELECT * FROM `foo` ' with 0 args
2014-09-02 14:20:57,794 [DEBUG] StatementExecutor query of 'SELECT * FROM `foo` ' returned 1 results
2014-09-02 14:20:57,794 [DEBUG] BaseMappedStatement prepared statement 'UPDATE `foo` SET `val` = 65809 ' with 0 args
2014-09-02 14:20:57,794 [DEBUG] BaseMappedStatement prepared statement 'SELECT * FROM `foo` ' with 0 args
2014-09-02 14:20:57,794 [DEBUG] StatementExecutor query of 'SELECT * FROM `foo` ' returned 1 results
2014-09-02 14:20:57,795 [DEBUG] StatementExecutor query of 'SELECT COUNT(*) FROM `foo` WHERE `id` = ? ' returned 1
2014-09-02 14:20:57,795 [DEBUG] BaseMappedStatement update data with statement 'UPDATE `foo` SET `val` = ?, `equal` = ?, `string` = ? WHERE `id` = ?' and 4 args, changed 1 rows
2014-09-02 14:20:57,795 [TRACE] BaseMappedStatement update arguments: [1232131321, 0, null, 1]
2014-09-02 14:20:57,795 [DEBUG] BaseMappedStatement updating-id with statement 'UPDATE `foo` SET `id` = ? WHERE `id` = ?' and 2 args, changed 1 rows
2014-09-02 14:20:57,795 [TRACE] BaseMappedStatement updating-id arguments: [2, 1]
2014-09-02 14:20:57,795 [DEBUG] BaseMappedStatement query-for-id using 'SELECT * FROM `foo` WHERE `id` = ?' and 1 args, got no results
2014-09-02 14:20:57,795 [TRACE] BaseMappedStatement query-for-id arguments: [1]
2014-09-02 14:20:57,795 [DEBUG] BaseMappedStatement query-for-id using 'SELECT * FROM `foo` WHERE `id` = ?' and 1 args, got 1 result
2014-09-02 14:20:57,795 [TRACE] BaseMappedStatement query-for-id arguments: [2]
2014-09-02 14:20:57,796 [DEBUG] BaseMappedStatement prepared statement 'SELECT * FROM `foo` ' with 0 args
2014-09-02 14:20:57,796 [DEBUG] BaseMappedStatement prepared statement 'SELECT * FROM `foo` ' with 0 args
2014-09-02 14:20:57,797 [DEBUG] BaseMappedStatement prepared statement 'SELECT * FROM `foo` ' with 0 args
2014-09-02 14:20:57,797 [DEBUG] BaseMappedStatement prepared statement 'SELECT * FROM `foo` ' with 0 args
2014-09-02 14:20:57,797 [DEBUG] BaseMappedStatement prepared statement 'SELECT * FROM `foo` ' with 0 args
2014-09-02 14:20:57,798 [DEBUG] BaseMappedStatement prepared statement 'SELECT * FROM `foo` ' with 0 args
2014-09-02 14:20:57,806 [DEBUG] StatementExecutor query of 'SELECT COUNT(*) FROM `foo`' returned 1
2014-09-02 14:20:57,807 [INFO] TableUtils dropping table 'foo'
2014-09-02 14:20:57,808 [INFO] TableUtils ignoring drop error 'org.h2.jdbc.JdbcSQLException: Table "FOO" not found; SQL statement:
DROP TABLE `foo`  [42102-128]' for statement: DROP TABLE `foo` 
2014-09-02 14:20:57,808 [INFO] TableUtils creating table 'foo'
2014-09-02 14:20:57,808 [INFO] TableUtils executed create table statement changed 0 rows: CREATE TABLE `foo` (`id` INTEGER AUTO_INCREMENT , `val` INTEGER , `equal` INTEGER , `string` VARCHAR(255) , PRIMARY KEY (`id`) ) 
2014-09-02 14:20:57,808 [DEBUG] BaseMappedStatement insert data with statement 'INSERT INTO `foo` (`val` ,`equal` ,`string` ) VALUES (?,?,?)' and 3 args, changed 1 rows
2014-09-02 14:20:57,809 [TRACE] BaseMappedStatement insert arguments: [1232131321, 0, null]
2014-09-02 14:20:57,809 [DEBUG] BaseMappedStatement assigned id '1' from keyholder to 'id' in Foo object
2014-09-02 14:20:57,809 [DEBUG] BaseMappedStatement query-for-id using 'SELECT * FROM `foo` WHERE `id` = ?' and 1 args, got 1 result
2014-09-02 14:20:57,809 [TRACE] BaseMappedStatement query-for-id arguments: [1]
2014-09-02 14:20:57,809 [DEBUG] BaseMappedStatement delete data with statement 'DELETE FROM `foo` WHERE `id` = ?' and 1 args, changed 1 rows
2014-09-02 14:20:57,809 [TRACE] BaseMappedStatement delete arguments: [1]
2014-09-02 14:20:57,809 [DEBUG] BaseMappedStatement query-for-id using 'SELECT * FROM `foo` WHERE `id` = ?' and 1 args, got no results
2014-09-02 14:20:57,809 [TRACE] BaseMappedStatement query-for-id arguments: [1]
2014-09-02 14:20:57,809 [DEBUG] BaseMappedStatement insert data with statement 'INSERT INTO `foo` (`val` ,`equal` ,`string` ) VALUES (?,?,?)' and 3 args, changed 1 rows
2014-09-02 14:20:57,809 [TRACE] BaseMappedStatement insert arguments: [1232131321, 0, null]
2014-09-02 14:20:57,809 [DEBUG] BaseMappedStatement assigned id '2' from keyholder to 'id' in Foo object
2014-09-02 14:20:57,810 [DEBUG] BaseMappedStatement query-for-id using 'SELECT * FROM `foo` WHERE `id` = ?' and 1 args, got 1 result
2014-09-02 14:20:57,810 [TRACE] BaseMappedStatement query-for-id arguments: [2]
2014-09-02 14:20:57,810 [DEBUG] BaseMappedStatement delete-collection with statement 'DELETE FROM `foo` WHERE `id` IN (?) ' and 1 args, changed 1 rows
2014-09-02 14:20:57,810 [TRACE] BaseMappedStatement delete-collection arguments: [2]
2014-09-02 14:20:57,810 [DEBUG] BaseMappedStatement query-for-id using 'SELECT * FROM `foo` WHERE `id` = ?' and 1 args, got no results
2014-09-02 14:20:57,810 [TRACE] BaseMappedStatement query-for-id arguments: [2]
2014-09-02 14:20:57,810 [DEBUG] BaseMappedStatement insert data with statement 'INSERT INTO `foo` (`val` ,`equal` ,`string` ) VALUES (?,?,?)' and 3 args, changed 1 rows
2014-09-02 14:20:57,810 [TRACE] BaseMappedStatement insert arguments: [1232131321, 0, null]
2014-09-02 14:20:57,810 [DEBUG] BaseMappedStatement assigned id '3' from keyholder to 'id' in Foo object
2014-09-02 14:20:57,810 [DEBUG] BaseMappedStatement query-for-id using 'SELECT * FROM `foo` WHERE `id` = ?' and 1 args, got 1 result
2014-09-02 14:20:57,810 [TRACE] BaseMappedStatement query-for-id arguments: [3]
2014-09-02 14:20:57,811 [DEBUG] BaseMappedStatement delete-collection with statement 'DELETE FROM `foo` WHERE `id` IN (?) ' and 1 args, changed 1 rows
2014-09-02 14:20:57,811 [TRACE] BaseMappedStatement delete-collection arguments: [3]
2014-09-02 14:20:57,811 [DEBUG] BaseMappedStatement query-for-id using 'SELECT * FROM `foo` WHERE `id` = ?' and 1 args, got no results
2014-09-02 14:20:57,811 [TRACE] BaseMappedStatement query-for-id arguments: [3]
2014-09-02 14:20:57,811 [DEBUG] BaseMappedStatement insert data with statement 'INSERT INTO `foo` (`val` ,`equal` ,`string` ) VALUES (?,?,?)' and 3 args, changed 1 rows
2014-09-02 14:20:57,811 [TRACE] BaseMappedStatement insert arguments: [1232131321, 0, null]
2014-09-02 14:20:57,812 [DEBUG] BaseMappedStatement assigned id '4' from keyholder to 'id' in Foo object
2014-09-02 14:20:57,812 [DEBUG] BaseMappedStatement query-for-id using 'SELECT * FROM `foo` WHERE `id` = ?' and 1 args, got 1 result
2014-09-02 14:20:57,812 [TRACE] BaseMappedStatement query-for-id arguments: [4]
2014-09-02 14:20:57,812 [DEBUG] BaseMappedStatement prepared statement 'DELETE FROM `foo` ' with 0 args
2014-09-02 14:20:57,812 [DEBUG] BaseMappedStatement query-for-id using 'SELECT * FROM `foo` WHERE `id` = ?' and 1 args, got no results
2014-09-02 14:20:57,812 [TRACE] BaseMappedStatement query-for-id arguments: [4]
2014-09-02 14:20:57,813 [INFO] TableUtils dropping table 'foo'
2014-09-02 14:20:57,813 [INFO] TableUtils ignoring drop error 'org.h2.jdbc.JdbcSQLException: Table "FOO" not found; SQL statement:
DROP TABLE `foo`  [42102-128]' for statement: DROP TABLE `foo` 
2014-09-02 14:20:57,813 [INFO] TableUtils creating table 'foo'
2014-09-02 14:20:57,814 [INFO] TableUtils executed create table statement changed 0 rows: CREATE TABLE `foo` (`id` INTEGER AUTO_INCREMENT , `val` INTEGER , `equal` INTEGER , `string` VARCHAR(255) , PRIMARY KEY (`id`) ) 
2014-09-02 14:20:57,814 [DEBUG] BaseMappedStatement insert data with statement 'INSERT INTO `foo` (`val` ,`equal` ,`string` ) VALUES (?,?,?)' and 3 args, changed 1 rows
2014-09-02 14:20:57,814 [TRACE] BaseMappedStatement insert arguments: [1232131321, 0, null]
2014-09-02 14:20:57,814 [DEBUG] BaseMappedStatement assigned id '1' from keyholder to 'id' in Foo object
2014-09-02 14:20:57,814 [DEBUG] StatementExecutor executing raw query for: select * from foo
2014-09-02 14:20:57,815 [DEBUG] StatementExecutor executing raw query for: select * from foo
2014-09-02 14:20:57,815 [DEBUG] StatementExecutor executing raw query for: select id,val from foo
2014-09-02 14:20:57,815 [DEBUG] StatementExecutor running raw execute statement: delete from foo where id = ?
2014-09-02 14:20:57,815 [TRACE] StatementExecutor execute arguments: [2]
2014-09-02 14:20:57,816 [DEBUG] StatementExecutor running raw update statement: update foo set val = 100 where id = ?
2014-09-02 14:20:57,816 [TRACE] StatementExecutor update arguments: [2]
2014-09-02 14:20:57,817 [DEBUG] StatementExecutor disabled auto-commit on table foo before batch tasks
2014-09-02 14:20:57,817 [DEBUG] StatementExecutor re-enabled auto-commit on table foo after batch tasks
2014-09-02 14:20:57,817 [DEBUG] StatementExecutor query of 'SELECT COUNT(*) FROM `foo`' returned 1
2014-09-02 14:20:57,817 [DEBUG] BaseMappedStatement prepared statement 'SELECT COUNT(*) FROM `foo` ' with 0 args
2014-09-02 14:20:57,818 [DEBUG] BaseMappedStatement prepared statement 'SELECT * FROM `foo` ' with 0 args
2014-09-02 14:20:57,818 [DEBUG] StatementExecutor query of 'SELECT COUNT(*) FROM `foo` WHERE `id` = ? ' returned 1
2014-09-02 14:20:57,818 [DEBUG] BaseMappedStatement prepared statement 'SELECT * FROM `foo` ' with 0 args
2014-09-02 14:20:57,818 [DEBUG] StatementExecutor query-for-first of 'SELECT * FROM `foo` ' returned at least 1 result
Could not find Dao method: public default java.util.Spliterator java.lang.Iterable.spliterator()
Could not find Dao method: public default void java.lang.Iterable.forEach(java.util.function.Consumer)
2014-09-02 14:20:57,822 [INFO] TableUtils dropping table 'foo'
2014-09-02 14:20:57,823 [INFO] TableUtils ignoring drop error 'org.h2.jdbc.JdbcSQLException: Table "FOO" not found; SQL statement:
DROP TABLE `foo`  [42102-128]' for statement: DROP TABLE `foo` 
2014-09-02 14:20:57,823 [INFO] TableUtils creating table 'foo'
2014-09-02 14:20:57,824 [INFO] TableUtils executed create table statement changed 0 rows: CREATE TABLE `foo` (`id` INTEGER AUTO_INCREMENT , `val` INTEGER , `equal` INTEGER , `string` VARCHAR(255) , PRIMARY KEY (`id`) ) 
2014-09-02 14:20:57,824 [DEBUG] StatementExecutor query of 'SELECT COUNT(*) FROM `foo`' returned 0
2014-09-02 14:20:57,825 [INFO] TableUtils dropping table 'foo'
2014-09-02 14:20:57,826 [INFO] TableUtils ignoring drop error 'org.h2.jdbc.JdbcSQLException: Table "FOO" not found; SQL statement:
DROP TABLE `foo`  [42102-128]' for statement: DROP TABLE `foo` 
2014-09-02 14:20:57,826 [INFO] TableUtils creating table 'foo'
2014-09-02 14:20:57,826 [INFO] TableUtils executed create table statement changed 0 rows: CREATE TABLE `foo` (`id` INTEGER AUTO_INCREMENT , `val` INTEGER , `equal` INTEGER , `string` VARCHAR(255) , PRIMARY KEY (`id`) ) 
2014-09-02 14:20:57,827 [DEBUG] StatementExecutor query of 'SELECT COUNT(*) FROM `foo`' returned 0
Tests run: 60, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 0.066 sec 

Bug - Assigning Result Set Column Names is not working correctly

Hi,

I found that when I'm making select like this:

Dao<Model, ?> dao = DaoManager.createDao(dataSource, Model.class);
GenericRawResults<Map<String, Object>> results = dao.queryRaw("select id as SOME_ID, name as SOME_NAME from SOMETHING order by 1", new RawRowMapper<Map<String, Object>>() {
    @Override
    public Map<String, Object> mapRow(String[] columnNames, String[] resultColumns) throws SQLException {
        LinkedHashMap<String, Object> map = new LinkedHashMap<>();
        for (int i=0; i<columnNames.length; i++) {
            map.put(columnNames[i], resultColumns[i]);
        }
        return map;
    }
});

List<Map<String, Object>> list = results.getResults();

System.out.println( Json.toJson(list).toString() );

Console log:

[{"id":"0","name":"postgres 0"},{"id":"1","name":"postgres 1"},{"id":"2","name":"postgres 2"}]

As you can see columnNames in mapper return base column names instead of new one. This is very frustrating when you make select like this:

SELECT a.id ACCOUNT_ID, o.id ORDER_ID, a.name from ACCOUNT a, ORDER o

Result is that you will get in columnNames two times "id" as column name instead of "ACCOUNT_ID" and "ORDER_ID"

.gitignore does not ignore project files created by IntelliJ IDEA

I am using IntelliJ IDEA to build the latest version of ormlite-core for my Android mobile app project. After importing ormlite-core into IDEA, all of the IDEA project files showed up as potentially Git additions. Adding the following to .gitignore fixes this:

.idea
*.iml

Get ResultSet directly

Hi,

I suggest to add queryRaw method that custom mapper can use ResultSet directly instead of Column and Values only.

Example:

dao.queryRaw("SELECT * FROM TABLE", new ResultSetMapper<Object>() {
            @Override
            public Object map(int index, ResultSet r, StatementContext ctx) {
                ...
            }
        });

This is more open to developer.

Invalid package reference in library ormlite-core-4.49-SNAPSHOT.jar

Lint is showing me an error trying to build the apk in Android:

InvalidPackage: Package not included in Android
../../libs/ormlite-core-4.49-SNAPSHOT.jar: Invalid package reference in library; 
not included in Android:     javax.persistence. 
Referenced from com.j256.ormlite.misc.JavaxPersistenceImpl.

master branch build error (javax.persistence dependency) on ubuntu

I'm trying to build the master branch of ormlite-core (and ormlite-android) because I need the new commits about CursorLoader and CursorAdapter.

I use ubuntu 14.04. I just cloned the github repo and launched mvn install.

Here is what I get : JavaxPersistenceImpl.java:[6,24] error: package javax.persistence does not exist.

I saw in the pom that the javax.persistence dependency has the scope "test". It may be the cause of the issue. If it is, how did you build until now ?!!

Problems of default implementation of iterator in BaseDaoImpl and LazyForeignCollection.

Hi!

The current implementation of the aforementioned iterator (it’s the same implementation at the end) has issues with backward movement operations like first() or previous (). See the commented out test which works for EagerForeigjnCollection. This happens, because the implementation (H2 for the test environment, but the same is true for the JDBC in general) creates only forward cursors. And of course they can’t move backwards. We explicitly need a bidirectional cursor for this. The reason why it already works in Android implementation is that we already always get bidirectional cursors in Android.

A possible solution: we need a new flag for the explicit bidirectional cursor or result set in the DatabaseConnection. And in all situations like this we should use this flag explicitly. For example, in the case of iterator we would enforce the scrollable cursor instead of forward cursor as a result of using DatabaseConnection.DEFAULT_RESULT_FLAGS now. Of course, all implementation should also respect this flag as they already do this with DatabaseConnection.DEFAULT_RESULT_FLAGS. If they need to do so because the usually created cursor isn’t scrollable. Once again see the Android as a contra example.

Otherwise this kind of iterator should have a comment, that it can’t be used for backward moving.

DateTimeType isn't valid for version

Hi!
I'm currently using ormlite 4.48 and saw that it's not possible to use a org.joda.time.DateTime object as a version.

@DatabaseField(version = true)
private DateTime modified;

will lead to

Caused by: java.lang.IllegalArgumentException: Field modified is not a valid type to be a version field
    at com.j256.ormlite.field.FieldType.<init>(FieldType.java:267)
    at com.j256.ormlite.field.FieldType.createFieldType(FieldType.java:957)
    at com.j256.ormlite.table.DatabaseTableConfig.extractFieldTypes(DatabaseTableConfig.java:208)
    at com.j256.ormlite.table.DatabaseTableConfig.fromClass(DatabaseTableConfig.java:146)
    at com.j256.ormlite.table.TableInfo.<init>(TableInfo.java:53)
    at com.j256.ormlite.dao.BaseDaoImpl.initialize(BaseDaoImpl.java:151)
    at com.j256.ormlite.dao.BaseDaoImpl.<init>(BaseDaoImpl.java:128)
    at com.j256.ormlite.dao.BaseDaoImpl.<init>(BaseDaoImpl.java:107)
    at org.obehave.persistence.impl.SubjectDaoImpl.<init>(SubjectDaoImpl.java:15)
    ... 41 more

Is this intentional?
If not, and if it's as simple as overriding isValidForVersion() and moveToNextValue(Object) as done in BaseDateType, I would be happy to try that and create a pull request.

Fresh maven build won't compile - JellyBeanApiCompatibility

First I had to delete the gpg plugin from the pom because i don't have the right signing certificate. Then I had to download and build ormlite-core because I couldn't find the 4.48-SNAPSHOT repository.

After that, here's what I get when building on my mac using java7

0 16:56 /Users/mike/Projects/ormlite-android $ mvn clean install
[INFO] Scanning for projects...
[WARNING]
[WARNING] Some problems were encountered while building the effective model for com.j256.ormlite:ormlite-android:jar:4.48-SNAPSHOT
[WARNING] The expression ${version} is deprecated. Please use ${project.version} instead.
[WARNING]
[WARNING] It is highly recommended to fix these problems because they threaten the stability of your build.
[WARNING]
[WARNING] For this reason, future Maven versions might no longer support building such malformed projects.
[WARNING]
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building ORMLite Android 4.48-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-clean-plugin:2.4.1:clean (default-clean) @ ormlite-android ---
[INFO] Deleting /Users/mike/Projects/ormlite-android/target
[INFO]
[INFO] --- maven-enforcer-plugin:1.0:enforce (enforce-maven) @ ormlite-android ---
[INFO]
[INFO] --- replacer:1.5.0:replace (validate) @ ormlite-android ---
[INFO] Replacement run on 1 file.
[INFO]
[INFO] --- maven-resources-plugin:2.5:resources (default-resources) @ ormlite-android ---
[debug] execute contextualize
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 2 resources
[INFO]
[INFO] --- maven-compiler-plugin:2.3.1:compile (default-compile) @ ormlite-android ---
[INFO] Compiling 19 source files to /Users/mike/Projects/ormlite-android/target/classes
[INFO] -------------------------------------------------------------
[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] /Users/mike/Projects/ormlite-android/src/main/java/com/j256/ormlite/android/compat/JellyBeanApiCompatibility.java:[5,17] error: cannot find symbol

[ERROR] package android.os
/Users/mike/Projects/ormlite-android/src/main/java/com/j256/ormlite/android/compat/JellyBeanApiCompatibility.java:[34,16] error: cannot find symbol

[ERROR] class JellyBeanCancellationHook
/Users/mike/Projects/ormlite-android/src/main/java/com/j256/ormlite/android/compat/JellyBeanApiCompatibility.java:[37,33] error: cannot find symbol

[INFO] 3 errors
[INFO] -------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.264s
[INFO] Finished at: Sat Nov 16 16:57:02 PST 2013
[INFO] Final Memory: 16M/310M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.1:compile (default-compile) on project ormlite-android: Compilation failure: Compilation failure:
[ERROR] /Users/mike/Projects/ormlite-android/src/main/java/com/j256/ormlite/android/compat/JellyBeanApiCompatibility.java:[5,17] error: cannot find symbol
[ERROR]
[ERROR] package android.os
[ERROR] /Users/mike/Projects/ormlite-android/src/main/java/com/j256/ormlite/android/compat/JellyBeanApiCompatibility.java:[34,16] error: cannot find symbol
[ERROR]
[ERROR] class JellyBeanCancellationHook
[ERROR] /Users/mike/Projects/ormlite-android/src/main/java/com/j256/ormlite/android/compat/JellyBeanApiCompatibility.java:[37,33] error: cannot find symbol
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException

1 16:57 /Users/mike/Projects/ormlite-android $

Log more when a field is not found

we got this crash on Crittercism pretty often :

Caused by: java.sql.SQLException: Could not find declared field with name 'modificationDate' for class xxx.WidgetSummary
114 at com.j256.ormlite.table.DatabaseTableConfig.convertFieldConfigs(DatabaseTableConfig.java:242)
115 at com.j256.ormlite.table.DatabaseTableConfig.extractFieldTypes(DatabaseTableConfig.java:101)
116 at com.j256.ormlite.dao.BaseDaoImpl.initialize(BaseDaoImpl.java:151)
117 at com.j256.ormlite.dao.BaseDaoImpl.<init>(BaseDaoImpl.java:126)
118 at com.j256.ormlite.dao.BaseDaoImpl.<init>(BaseDaoImpl.java:117)
119 

We have proguarded the field, it is found 99.999% of the time, but we some time have crashes like this one. The rate is approximately 1 for 100 million launches. Pretty low, not related to a specific device.

Would it be possible to log all the fields in this case, so that we can understand what happens to them.

UniqueCombo and DAO

Hi, I've a table with 3 column as primarykey and I've set the class like this:

public class myTab {

    @DatabaseField(uniqueCombo = true, uniqueIndexName = "PK_Primary", width = 3)
    public String myField1;
    @DatabaseField(uniqueCombo = true, uniqueIndexName = "PK_Primary", width = 3)
    public String myField2;
    @DatabaseField(uniqueCombo = true, uniqueIndexName = "PK_Primary")
    public int myIntField;
    @DatabaseField(width = 8)
    public String myValueNoKey;

but now I don't know how can I make a DAO for this class...

Dao<myTab, ?? AND HERE ??> dao

many thanks...

generic inheritance error

I use ormlite-android 4.48 + ormlite-core 4.48 and get the following exception:
java.sql.SQLException: queryForOne from database failed: SELECT * FROM``basemodel``WHERE``_id``= ?
Is seems that BaseParentRelationModel<P extends BaseModel> can't be resolved.

executed code:

E = CategoryModel
List<E> _ItemList = null;
    try {
        QueryBuilder<E, Integer> _QueryBuilder = this.dao.queryBuilder();
        _QueryBuilder.orderBy(this.sortColumn, true);

        PreparedQuery<E> _PreparedQuery = _QueryBuilder.prepare();
        _ItemList = this.dao.query(_PreparedQuery);
    } catch (SQLException e) {
        Log.e(this.getClass().getName(), "" + e.getMessage());
    }

model class:

    @DatabaseTable(tableName = CategoryModel.TABLENAME)
    public class CategoryModel extends BaseParentRelationModel<CategoryModel> {
    ...
    }

inheritance class 1:

    public abstract class BaseParentRelationModel<P extends BaseModel> extends BaseModel {
    @DatabaseField(columnName = COLUMN_PARENT, canBeNull = true,
            foreignColumnName = P.COLUMN_ID, foreign = true, foreignAutoRefresh = true, foreignAutoCreate = true,
            maxForeignAutoRefreshLevel = 3)
    public P parent;
    public static final String COLUMN_PARENT = "parent_id";
    }

inheritance class 2:

    public abstract class BaseModel {
    @DatabaseField(columnName = COLUMN_ID, generatedId = true)
    public long id;
    public static final String COLUMN_ID = "_id";
    ...
    }

Feature request: auto upgrade schema

Keeping track of changes to classes, maintaining a version number and writing manual 'scripts' in onUpgrade() is error-prone and becomes unwieldy as the number of releases grows.

OrmLite could automate this to varying extents. Initially for add/remove columns, and probably also for changing data type or size where the data is compatible.

An initial implementation could compare the 'create table' statement generated from the Class with the current database table structure and if there is any mismatch: rename the table, create a new table, copy all the data across, then delete the old renamed table.

Later enhancements could analyse the mismatches and generate 'alter table' statements for faster operation but the above might be acceptable for many applications in the meantime.

appendValue in In.java ignores SelectArgs

My query contains:
List selectArgs = new ArrayList<>();
for (String issuerName : issuerNames) {
selectArgs.add(new SelectArg(issuerName));
}
bondQb.where().in(Bond.COLUMN_NAME_ISSUER_NAME, selectArgs);

In class "In.java" after foreach loop result query do not contains selection arguments: SELECT isin FROM bond WHERE issuer IN (? ,? ) - here are just spaces.

I can't use simple List in my "in" query because of issue with unescaped apostrophies.

Adding a getter on DatabaseFieldConfig fieldConfig in FieldType ?

Is it possible to add a getter on DatabaseFieldConfig fieldConfig in FieldType ?

I ask that because I am doing a little admin interface, and I need to walk along the models. I start with a DAO, then get a TableInfo, and then I need to access to the tableInfos of the foreign fields.

Feature request: Add support for table schema

It would be very convenient to have support for various table schema (Postgres schema). Not only using annotations but also at runtime.

We use sharded tables, they are identical but we'd like to direct query to particular schema shard.

writeConfigFile() generates Enum name with $ sign

writeConfigFile() generates Enum name with $ sign using this Enum code. Produces the following error:

 Caused by: java.lang.IllegalArgumentException: Invalid class is not an Enum for unknownEnumValue: com.jahd.omdmovil.modelo.Color$1#NINGUNO
            at com.j256.ormlite.field.DatabaseFieldConfigLoader.readField(DatabaseFieldConfigLoader.java:335)
            at com.j256.ormlite.field.DatabaseFieldConfigLoader.fromReader(DatabaseFieldConfigLoader.java:54)
            at com.j256.ormlite.table.DatabaseTableConfigLoader.readFields(DatabaseTableConfigLoader.java:163)
            at com.j256.ormlite.table.DatabaseTableConfigLoader.fromReader(DatabaseTableConfigLoader.java:65)
            at com.j256.ormlite.table.DatabaseTableConfigLoader.loadDatabaseConfigFromReader(DatabaseTableConfigLoader.java:32)
            at com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper.<init>(OrmLiteSqliteOpenHelper.java:85)
            at com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper.<init>(OrmLiteSqliteOpenHelper.java:54)
            at com.jahd.omdmovil.OrmHelper.<init>(OrmHelper.java:54)

Investigated and it occurs because in the config file, the problematic line is:

unknownEnumValue=com.jahd.omdmovil.modelo.Color$1#NINGUNO

And when com.jahd.omdmovil.modelo.Color$1 is passed to:

            try {
                enumClass = Class.forName(parts[0]);
            } catch (ClassNotFoundException e) {
                throw new IllegalArgumentException("Unknown class specified for unknownEnumValue: " + value);
            }
            Object[] consts = enumClass.getEnumConstants();

the consts array is null. The workaround was replacing the problematic string with:

unknownEnumValue=com.jahd.omdmovil.modelo.Color#NINGUNO

Notice the missing dollar sign. However I don't know if it's better to fix the writeConfigFile() method, or the readField() method.

Jpa OneToMany not works.

In JavaxPersistence, there is no OneToMany in considered. Have to do something like this

@ForeignCollectionField(foreignFieldName = "article")
@OneToMany(mappedBy = "article", fetch = FetchType.LAZY, cascade = {CascadeType.ALL})
private Collection<Comment> comments = Sets.newHashSet();

Cannot store nested parts of JSON request using robospice and ormlite

Hi we using RoboSpice with ORMLite and SpringAndroidSpiceRequest to read JSON info from webpage and write to SQLite database.

We are using the newest JSON mapper MappingJackson2HttpMessageConverter.

    // Web services support JSON responses
    MappingJackson2HttpMessageConverter jsonConverter = new  MappingJackson2HttpMessageConverter();
    FormHttpMessageConverter formHttpMessageConverter = new FormHttpMessageConverter();
    StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter();
    final List<HttpMessageConverter<?>> listHttpMessageConverters = restTemplate.getMessageConverters();

We have tried to read nested JSON queries like the below example, we can read and store to database, the first level of JSON (page, total), but we can't store the next levet of the JSON array, All the "schedule_date" entries.

We have looked at this example (and many more) as the best example to store the JSON data. But it doesn't work for us. RoboSpice persist JSON array with OrmLite

Question: How do we get to read and write the nested JSON keys and values, We are stumped ! :O

JSON:

{
"page": 2,
"total": 5,
"result":
[
{
"schedule_date": "2013-08-03"
},
{
"schedule_date": "2013-09-03"
},
{
"schedule_date": "2013-10-03"
},
{
"schedule_date": "2013-11-03"
},
{
"schedule_date": "2013-12-03"
}
]
}

BroadcastResult.java:

        import java.util.Collection;
        import java.util.List;
        import com.j256.ormlite.field.DatabaseField;
        import com.j256.ormlite.table.DatabaseTable;
        import com.j256.ormlite.field.ForeignCollectionField;
        import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

        @JsonIgnoreProperties(ignoreUnknown = true)
        @DatabaseTable(tableName="BroadcastResult")
        public class BroadcastResult {

            @DatabaseField(id = true)
            private int page;

            @DatabaseField
            private int total;

            @ForeignCollectionField(eager = false)
            private Collection<Broadcast> result;

            public int getPage() {
                return page;
            }

            public void setPage(int page) {
                this.page = page;
            }

            public int getTotal() {
                return total;
            }

            public void setTotal(int total) {
                this.total = total;
            }

            public Collection<Broadcast> getResult() {
                return result;
            }

            public void setResult(Collection<Broadcast> result) {
                this.result = result;
            }
        }

Broadcast.java:

        import com.j256.ormlite.field.DatabaseField;
        import com.j256.ormlite.table.DatabaseTable;
        import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

        @JsonIgnoreProperties(ignoreUnknown = true)
        @DatabaseTable(tableName="Broadcast")
        public class Broadcast {

            @DatabaseField(id = true)
            private String schedule_date;

            @DatabaseField(foreign = true)
            private BroadcastResult result;

            public String getScheduleDate() {
                return schedule_date;
            }

            public void setScheduleDate(String schedule_date) {
                this.schedule_date = schedule_date;
            }

            public void setBroadcastResult(BroadcastResult result) {
                this.result = result;
            }

            public BroadcastResult getBroadcastResult() {
                return result;
            }   
        }

We got this error, that we do not understand.
Logcat: SQLiteLog(10637): (1) no such column: result_id

@DatabaseField(foreign = true) // also tried (foreign = true, ColumnName="result")
private BroadcastResult result;

The complete log for the run test can be seen here: https://gist.github.com/anonymous/7760344

Wrong behavior of the lazy collection iterator.

This test (a885740) tests the state of the iterator after delete. It works as it should only with eager collection iterator. We have an object with collection of 3 depended objects. We get the collection's iterator and move to the first, then to the second element, delete the second element and move to the next element and back. After that we read the current object.

With eager collection this is the first element, because the iterator is coherent with the underlying list. Right now we can't test the lazy collection iterator because the underlying cursor can't move backwards, see another ticket. But it works on the Android and this test fails there. The element we get there at the end is deleted second one. This is because the delete of the lazy collection iterator goes direct to the DB and the collection and iterator itself don't get know that something has been changed.

So we need a way to get the iterator informed, so he can react on the delete and get the new state or skip the deleted elements. Or iterator should delete the element itself. For the second scenario the bitmap can be used for storing the mask of deleted elements, but this isn't a very good solution, maybe there are better ones.

IllegalArgumentException: Foreign field class Xyz does not have id field

I have an abstract base class Entity for all classes in my model that have an independent lifecycle. This class provides the id attribute as well as other common lifecycle attributes like a "boolean deleted" attribute.

When I try to create a Dao for a concrete Derived class that extends the base class Entity I get the following Exception:

ava.lang.IllegalArgumentException: Foreign field class com.foo.model.Bar does not have id field
at com.j256.ormlite.field.FieldType.configDaoInformation(FieldType.java:308)
at com.j256.ormlite.dao.BaseDaoImpl.initialize(BaseDaoImpl.java:201)
at com.j256.ormlite.dao.BaseDaoImpl.(BaseDaoImpl.java:128)
at com.j256.ormlite.dao.BaseDaoImpl.(BaseDaoImpl.java:119)
at com.j256.ormlite.dao.BaseDaoImpl$5.(BaseDaoImpl.java:921)
at com.j256.ormlite.dao.BaseDaoImpl.createDao(BaseDaoImpl.java:921)
at com.j256.ormlite.dao.DaoManager.createDao(DaoManager.java:72)
at com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper.getDao(OrmLiteSqliteOpenHelper.java:279)
at com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper.getRuntimeExceptionDao(OrmLiteSqliteOpenHelper.java:295)

It seems it that the com.j256.ormlite.field.FieldType.configDaoInformation method should look at inherited id attribute from the base class Entity and treat them the same as if they were in the derived class. If I find time I will try and provide a Pull request that fixes this. Please let me know if there is a good reason why I should not bother trying ;-)

Dynamic table name.

I'm facing this requirement when doing sharding of tables:

I currently cannot set the table name dynamically, and it has to be set using a static annotation. For most times, this is alright, but I need this to be set dynamically.

Got an idea how to do this with the current implementation?

Support for primary keys that aren't INTs

Hi again.
I have set up most of my tables to include a primary key which is BINARY(8). This allows for a 16^16 possible rows, which is adequate for me.
OrmLite's (id=true) doesn't play well with this as it expects the field to be an integer.
Is there plans to support this functionality? Or maybe it's already supported?
Thanks in advance.

Documentaion

I think project needs more documentation. Code examples is not enough and I think this lack of docs can discourage some developers of using this quite interesting ORM ; )

Support for sharded installations?

Hi there.
I started using the library and have gotten to a point where I'm stuck. My infrastructure contains many shards (each database contains the same table names, most of the time), and what changes is the database name.
However, I cannot seem to find an easy way how to query a table from different databases. It seems that in order to use OrmLite, one needs to first select a database and then use the different methods to interact with tables: querying, inserting, updating, etc.
So, in short: How to support shards easily?
Thanks.

4.50?

There were no releases since 2013. Are there any plans on continuing support?

Error on createTableIfNotExists (PgSQL)

This code does'n work if table "Citizens" already exixts

TableUtils.createTableIfNotExists(injector.getInstance(ConnectionSource.class), Citizen.class);

Error log:
10:24:34,354 ERROR [stderr](ServerService Thread Pool -- 23) java.sql.SQLException: SQL statement failed: CREATE SEQUENCE "Citizens_id_seq"
10:24:34,354 ERROR [stderr](ServerService Thread Pool -- 23) at com.j256.ormlite.misc.SqlExceptionUtil.create(SqlExceptionUtil.java:22)
10:24:34,354 ERROR [stderr](ServerService Thread Pool -- 23) at com.j256.ormlite.table.TableUtils.doStatements(TableUtils.java:468)
10:24:34,355 ERROR [stderr](ServerService Thread Pool -- 23) at com.j256.ormlite.table.TableUtils.doCreateTable(TableUtils.java:442)
10:24:34,355 ERROR [stderr](ServerService Thread Pool -- 23) at com.j256.ormlite.table.TableUtils.createTable(TableUtils.java:220)
10:24:34,355 ERROR [stderr](ServerService Thread Pool -- 23) at com.j256.ormlite.table.TableUtils.createTableIfNotExists(TableUtils.java:61)

Mapping:
@entity(name = "Citizens")
public class Citizen {
@id
@GeneratedValue
private Long id;
...
}

Provide parametrized filter method

Look at those 2 methods I wrote in my application (getQuery and getRelationsQuery returns a QueryBuilder instance):

public List<Document> getRelatedDocuments(Document document) throws SQLException {
    return this.getQuery().where().in("id", getRelationsQuery(document)).query();
}

public List<Document> getUnrelatedDocuments(Document document) throws SQLException {
    return this.getQuery().where().notIn("id", getRelationsQuery(document)).query();
}

You see that they are almost equal, apart from the "in" vs "notIn". I would like to refactor them to a single method, and since I can't pass a method as a parameter, a method with a signature similar to clause(ClauseType type, String columnName, Object value) would be really appreciated, so that I can write

public List<Document> getRelatedDocuments(Document document) throws SQLException {
    return getDocuments(ClauseType.IN, document);
}

public List<Document> getUnrelatedDocuments(Document document) throws SQLException {
    return getDocuments(ClauseType.NOT_IN, document);
}

public List<Document> getDocuments(ClauseType type, Document document) throws SQLException {
    return this.getQuery().where().clause(type, "id", getRelationsQuery(document)).query();
}

Greatly reducing code duplication.

Of course I have an example for in/notIn, but same reasoning could be applied to eq, lt, le....

It makes perfect sense to keep current methods which are more straightforward to use, but adding a more generic one in some situations could be very handy.

Cannot persist class with parameterized ForeignCollection in supertype.

Trying to persist (install table) of the following construct fails

abstract class AbstractTest<T> {
    @ForeignCollectionField
    ForeignCollection<T> collection;
}

@DatabaseTable
public class Test extends AbstractTest<String> {
}

with error java.lang.ClassCastException: libcore.reflect.TypeVariableImpl cannot be cast to java.lang.Class on Android.

The error originates from line 370 in FieldType.java

Class<?> collectionClazz = (Class<?>) genericArguments[0];

since genericArguments[0] is of type libcore.reflect.TypeVariableImpl. This is Android specific so I'm not sure if it runs on other platforms.

Anyway I think in this case the parameterized type needs to be taken from the superclass with

((ParameterizedType) parentClass.getGenericSuperclass()).getActualTypeArguments()

No fields have a DatabaseField annotation in class

04-10 12:30:15.175 19820-19820/com.diaryinc.diaryoffice E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.diaryinc.diaryoffice, PID: 19820
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.diaryinc.diaryoffice/com.diaryinc.diaryoffice.SplashActivity}: java.lang.IllegalArgumentException: No fields have a DatabaseField annotation in class com.diaryinc.diaryoffice.database.entities.SimpleDataContract
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2394)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2452)
at android.app.ActivityThread.access$900(ActivityThread.java:172)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1302)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5586)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.IllegalArgumentException: No fields have a DatabaseField annotation in class com.diaryinc.diaryoffice.database.entities.SimpleDataContract
at com.j256.ormlite.table.DatabaseTableConfig.extractFieldTypes(DatabaseTableConfig.java:215)
at com.j256.ormlite.table.DatabaseTableConfig.fromClass(DatabaseTableConfig.java:146)
at com.j256.ormlite.table.TableInfo.(TableInfo.java:53)
at com.j256.ormlite.dao.BaseDaoImpl.initialize(BaseDaoImpl.java:151)
at com.j256.ormlite.dao.BaseDaoImpl.(BaseDaoImpl.java:128)
at com.j256.ormlite.dao.BaseDaoImpl.(BaseDaoImpl.java:107)
at com.j256.ormlite.dao.BaseDaoImpl$4.(BaseDaoImpl.java:907)
at com.j256.ormlite.dao.BaseDaoImpl.createDao(BaseDaoImpl.java:907)
at com.j256.ormlite.dao.DaoManager.createDao(DaoManager.java:70)
at com.j256.ormlite.table.TableUtils.createTable(TableUtils.java:218)
at com.j256.ormlite.table.TableUtils.createTable(TableUtils.java:53)
at com.diaryinc.diaryoffice.database.helpers.DatabaseHelper.createTable(DatabaseHelper.java:54)
at com.diaryinc.diaryoffice.database.helpers.DatabaseHelper.onCreate(DatabaseHelper.java:35)
at com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper.onCreate(OrmLiteSqliteOpenHelper.java:209)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:252)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
at com.j256.ormlite.android.AndroidConnectionSource.getReadWriteConnection(AndroidConnectionSource.java:66)
at com.j256.ormlite.dao.BaseDaoImpl.create(BaseDaoImpl.java:308)
at com.diaryinc.diaryoffice.SplashActivity.doSampleDatabaseStuff(SplashActivity.java:48)
at com.diaryinc.diaryoffice.SplashActivity.onCreate(SplashActivity.java:29)
at android.app.Activity.performCreate(Activity.java:5451)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2358)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2452)
            at android.app.ActivityThread.access$900(ActivityThread.java:172)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1302)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5586)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
            at dalvik.system.NativeStart.main(Native Method)

JPA @IdClass annotation support

Class:

@IdClass(value = TProductPK.class)
@Entity
@Table(name = "t_product")
public class TProduct {

    @Id
    @Column(name = "markingOfTheGood")
    private String code;

    @Id
    @Column(name = "status")
    private int status = 0;
...
}

JPA specification says:

The IdClass annotation is applied to an entity class or a mapped superclass to specify a composite
primary key class that is mapped to multiple fields or properties of the entity
Example:

@IdClass(com.acme.EmployeePK.class)
@Entity
public class Employee {
@Id String empName;
@Id Date birthDay;
...
}

But I have:

java.sql.SQLException: More than 1 idField configured for class class ru.crystals.pos.datasource.jdbc.example.TProduct (FieldType:name=markingOfTheGood,class=TProduct,FieldType:name=status,class=TProduct)
    at com.j256.ormlite.table.TableInfo.<init>(TableInfo.java:80)
    at com.j256.ormlite.table.TableInfo.<init>(TableInfo.java:53)
    at com.j256.ormlite.dao.BaseDaoImpl.initialize(BaseDaoImpl.java:151)
    at com.j256.ormlite.dao.BaseDaoImpl.<init>(BaseDaoImpl.java:128)
    at com.j256.ormlite.dao.BaseDaoImpl.<init>(BaseDaoImpl.java:107)
    at com.j256.ormlite.dao.BaseDaoImpl$4.<init>(BaseDaoImpl.java:907)
    at com.j256.ormlite.dao.BaseDaoImpl.createDao(BaseDaoImpl.java:907)
    at com.j256.ormlite.dao.DaoManager.createDao(DaoManager.java:70)
    at com.j256.ormlite.field.FieldType.configDaoInformation(FieldType.java:341)
    at com.j256.ormlite.dao.BaseDaoImpl.initialize(BaseDaoImpl.java:201)
    at com.j256.ormlite.dao.BaseDaoImpl.<init>(BaseDaoImpl.java:128)
    at com.j256.ormlite.dao.BaseDaoImpl.<init>(BaseDaoImpl.java:107)
    at com.j256.ormlite.dao.BaseDaoImpl$4.<init>(BaseDaoImpl.java:907)
    at com.j256.ormlite.dao.BaseDaoImpl.createDao(BaseDaoImpl.java:907)
    at com.j256.ormlite.dao.DaoManager.createDao(DaoManager.java:70)

`BaseMappedQuery.columnPositions` caches column positions, causes problems when table changes.

A very rare bug we found using ORMLite on Android is that after a db upgrade, the columns to object fields are mapped in the incorrect order.

I looked at the ORMLite code today, and I think I found the cuase. BaseMepperQuery caches the column positions from the result set, as read from the database.

Our app clears its data from the server when a specific command is sent. Clear data as in drops tables, and creates them again, using TableUtils.

The following sequence of events will trigger this bug:

  1. App starts up, and upgrades db, appending new column to index 4 of db.
  2. Our (long running) sync service creates a DAO and does a query on the upgraded table. This populates the BaseMappedQuery.columnPositions cache, and doesn't update it again.
  3. The server sends the clear data command to the app. The app diligently drops and recreates all its tables. Unfortunately, the new column when table is recreated, is now at index 1, not 4.
  4. The sync starts, and reads a row from the table, and incorrectly assigns column index 4 (incorrect column) to new field in object, as read from the cache.
  5. All hell breaks loose.

I suggest a fix for this to either remove the cache completely (bad for performance), or shorten the life of the cache. Clear it after the row(s) have completed mapping. (I don't see a simple way of adding that though.)

Any other ideas that I missed for a fix?

As a workaround I clear the data-tables instead of drop and re create. This preserves the column order in the db.

foreignAutoCreate is ignored on update

The aforementioned parameter is ignored on update of the parent object. The instance of related class is only created, if the parent object also created, but not updated.

The probably solution is to extract the whole part (the complete if, responsible for this parameter) from MappedCreate.insert(), put it as protected method into the BaseMappedStatement class and call this method from the MappedUpdate.update() also.

foreignAutoCreate dont create inner object

I use robospice-ormlite version 1.4.14, which depends on ormlite-android 4.48 and ormlite-core 4.48.
Like the documentation said for foreignAutoCreate: "Set this to be true (default false) to have the foreign field automatically created using an internal DAO if its ID field is not set (null or 0)."

I used it like this:

@DatabaseTable(tableName = "parent")
public class Parent {
    @DatabaseField(columnName = "_id", generatedId = true)
    public long databaseId;

    @DatabaseField(columnName = "foreignId", foreign = true, foreignAutoCreate = true,
            foreignAutoRefresh = true, foreignColumnName = "child_api_id", canBeNull = false)
    public Child child;
...
}

@DatabaseTable(tableName = "child")
public class Child {
    @DatabaseField(columnName = "_id", generatedId = true)
    public long databaseId;

    @DatabaseField(columnName = "api_id", columnDefinition = "INTEGER UNIQUE ON CONFLICT REPLACE")
    public long child_api_id;
...
}

Parent object retrieved from json, so its child fields already instantiated, except databaseId, which is zero of course. I thought that, when i'll persist the parent, childs are also will be persisted because the databaseId field is zero. But it is not persisted, probably because the child_api_id not zero? Nonetheless the child_api_id are correctly persisted to Parent table in column "foreignId".

The reason i cannot use a _id field of Child as foreign, that it will change over time because of UNIQUE ON CONFLICT REPLACE. Also i cannot persist the Child before Parent manually, because this job is done by CacheManager of RoboSpice.

Best regards, Dmitriy.

Microseconds are not supported by SimpleDateFormat

String format = "yyyy-MM-dd HH:mm:ss.SSSSSS";
DateFormat dateFormat = new SimpleDateFormat(format);

The default date format at BaseDateType.java#L20 contains six digits after the decimal point.
However, as 'S' stands for miliseconds (which max out at 999), the first 3 digits after the decimal point are always 0.
For example, 1.567 seconds are printed as
00:00:01.000567 and not as 00:00:01.567 or 00:00:01.567000 as one would expect.

patch: support custom db objects (example: h2 spatial geometry and point)

hello,

i needed support for database specific return objects such as Point in H2.
i see that others had the same issue:

https://stackoverflow.com/questions/12220234/model-geometry-point-with-ormlite
https://stackoverflow.com/questions/14751386/using-postgis-with-ormlite

attached is a patch for using custom db objects and data types.

Here is a usage example:

the model:

@databasetable(tableName = "LOCATIONS")
public class Location
{
static final GeometryFactory geometryFactory = new GeometryFactory();

@DatabaseField(index=true)
String _name = "";
@DatabaseField(persisterClass = PointType.class)
Point _gps = geometryFactory.createPoint(new Coordinate(0, 0));

}

mapping of point type:

public class PointType extends BaseDataType
{
private static final PointType singleTon = new PointType();

public static PointType getSingleton() {
    return singleTon;
}

private PointType() {
    super(SqlType.OTHER);
}

public String getSqlOtherType()
{
    return "GEOMETRY";
}



/**
 * Here for others to subclass.
 */
protected PointType(SqlType sqlType, Class<?>[] classes) {
    super(sqlType, classes);
}

@Override
public Object parseDefaultString(FieldType fieldType, String defaultStr) throws SQLException {
    throw new SQLException("Default values for point types are not supported");
}

@Override
public Object resultToSqlArg(FieldType fieldType, DatabaseResults results, int columnPos) throws SQLException {
    return results.getObject(columnPos);
}

@Override
public Object javaToSqlArg(FieldType fieldType, Object obj) throws SQLException {
    return obj;
}

@Override
public boolean isValidForField(Field field) {
    return true;
}

@Override
public boolean isComparable() {
    return false;
}

@Override
public boolean isAppropriateId() {
    return false;
}

}

create a spatial index:

    locationDao
            .executeRaw("CREATE SPATIAL INDEX IF NOT EXISTS LOCATIONS_SPATIALINDEX ON LOCATIONS(_GPS)");

search for locations in the vicinity

Uploading ormlite2.diff.txt…
ormlite2.txt

of a gps coordinate:

    QueryBuilder<Location, Long> lqb = locationDao.getLocationDao()).queryBuilder();

    double[][] polygon = GeoUtils.polygone(lon, lat, km);
    StringBuffer b = new StringBuffer("_GPS && 'POLYGON ((");
    for (int i=0; i<5; i++)
    {
        b.append(polygon[i][0]);
        b.append(" ");
        b.append(polygon[i][1]);
        if (i != 4)
            b.append(",");
    }
    b.append("))'");

    lqb.where().raw(b.toString()).query()

ormlite1.txt
Uploading ormlite2.txt…

Exception raised on non-foreign field about maxForeignAutoRefreshLevel and foreignAutoRefresh

I'm using a build of ormlite-core from master (commit e653256) on Android.

I'm getting this runtime exception when creating a table:

java.lang.IllegalArgumentException: Field address1 has maxForeignAutoRefreshLevel set (2) but not foreignAutoRefresh is false
        at com.j256.ormlite.field.FieldType.<init>(FieldType.java:273)
        at com.j256.ormlite.table.DatabaseTableConfig.convertFieldConfigs(DatabaseTableConfig.java:249)
        at com.j256.ormlite.table.DatabaseTableConfig.extractFieldTypes(DatabaseTableConfig.java:116)

The relevant field has this definition:

@DatabaseField
private String address1;

In 4b3a3dd , you changed how the default recursion level is injected. Does this now change the level for all fields? Should there be a check that the field is actually a foreign one?

This problem never occurred for me when using ormlite-core 4.4.8 . I don't ever set the refresh level in my models.

ThreadLocal tomcat reload/undeploy

I have some problem while reloading/undeploying web application in tomcat

SEVERE: The web application [/test] created a ThreadLocal with key of type [com.j256.ormlite.field.FieldType$1] (value [com.j256.ormlite.field.FieldType$1@213fc48f]) and a value of type [com.j256.ormlite.field.FieldType.LevelCounters] (value [com.j256.ormlite.field.FieldType$LevelCounters@61819956]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak.
Sep 11, 2014 10:14:25 AM org.apache.catalina.loader.WebappClassLoader checkThreadLocalMapForLeaks
SEVERE: The web application [/test] created a ThreadLocal with key of type [com.j256.ormlite.field.FieldType$1] (value [com.j256.ormlite.field.FieldType$1@213fc48f]) and a value of type [com.j256.ormlite.field.FieldType.LevelCounters] (value [com.j256.ormlite.field.FieldType$LevelCounters@37a0f1d]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak.
Sep 11, 2014 10:14:25 AM org.apache.catalina.loader.WebappClassLoader checkThreadLocalMapForLeaks
SEVERE: The web application [/test] created a ThreadLocal with key of type [com.j256.ormlite.field.FieldType$1] (value [com.j256.ormlite.field.FieldType$1@213fc48f]) and a value of type [com.j256.ormlite.field.FieldType.LevelCounters] (value [com.j256.ormlite.field.FieldType$LevelCounters@42763ab3]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak.
Sep 11, 2014 10:14:25 AM org.apache.catalina.loader.WebappClassLoader checkThreadLocalMapForLeaks
SEVERE: The web application [/test] created a ThreadLocal with key of type [com.j256.ormlite.field.FieldType$1] (value [com.j256.ormlite.field.FieldType$1@213fc48f]) and a value of type [com.j256.ormlite.field.FieldType.LevelCounters] (value [com.j256.ormlite.field.FieldType$LevelCounters@6007dfdb]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak.

FieldTypeTest failed

cloned last revision and get error below when mvn package.

Failed tests: testFieldTypeConverter(com.j256.ormlite.field.FieldTypeTest):

Tests run: 986, Failures: 1, Errors: 0, Skipped: 2

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.