Import DaoGenerator from greenDAO

The jitpack.io build is facing issues. The code required for the code
generation is quite small, with a negligible build impact, so import it
directly to the repository from the fork and remove the dependency on
jitpack completely.

- Taken from https://codeberg.org/Freeyourgadget/greenDAO
- Original commit: 1998d7cd2d21f662c6044f6ccf3b3a251bbad341
This commit is contained in:
José Rebelo
2025-06-19 13:22:28 +01:00
parent 2961c38c04
commit e083eaa011
25 changed files with 3522 additions and 5 deletions
@@ -0,0 +1,217 @@
package ${contentProvider.javaPackage};
import android.content.ContentProvider;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import de.greenrobot.dao.DaoLog;
import ${schema.defaultJavaPackageDao}.DaoSession;
import ${entity.javaPackageDao}.${entity.classNameDao};
/* Copy this code snippet into your AndroidManifest.xml inside the
<application> element:
<provider
android:name="${contentProvider.javaPackage}.${contentProvider.className}"
android:authorities="${contentProvider.authority}"/>
*/
public class ${contentProvider.className} extends ContentProvider {
public static final String AUTHORITY = "${contentProvider.authority}";
public static final String BASE_PATH = "${contentProvider.basePath}";
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + BASE_PATH);
public static final String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE
+ "/" + BASE_PATH;
public static final String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE
+ "/" + BASE_PATH;
private static final String TABLENAME = ${entity.classNameDao}.TABLENAME;
private static final String PK = ${entity.classNameDao}.Properties.${entity.pkProperty.propertyName?cap_first}
.columnName;
<#assign counter = 0>
private static final int ${entity.className?upper_case}_DIR = ${counter};
private static final int ${entity.className?upper_case}_ID = ${counter+1};
private static final UriMatcher sURIMatcher;
static {
sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH);
sURIMatcher.addURI(AUTHORITY, BASE_PATH, ${entity.className?upper_case}_DIR);
sURIMatcher.addURI(AUTHORITY, BASE_PATH + "/#", ${entity.className?upper_case}_ID);
}
/**
* This must be set from outside, it's recommended to do this inside your Application object.
* Subject to change (static isn't nice).
*/
public static DaoSession daoSession;
@Override
public boolean onCreate() {
// if(daoSession == null) {
// throw new IllegalStateException("DaoSession must be set before content provider is created");
// }
DaoLog.d("Content Provider started: " + CONTENT_URI);
return true;
}
protected SQLiteDatabase getDatabase() {
if(daoSession == null) {
throw new IllegalStateException("DaoSession must be set during content provider is active");
}
return daoSession.getDatabase();
}
<#--
##########################################
########## Insert ##############
##########################################
-->
@Override
public Uri insert(Uri uri, ContentValues values) {
<#if contentProvider.isReadOnly()>
throw new UnsupportedOperationException("This content provider is readonly");
<#else>
int uriType = sURIMatcher.match(uri);
long id = 0;
String path = "";
switch (uriType) {
case ${entity.className?upper_case}_DIR:
id = getDatabase().insert(TABLENAME, null, values);
path = BASE_PATH + "/" + id;
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return Uri.parse(path);
</#if>
}
<#--
##########################################
########## Delete ##############
##########################################
-->
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
<#if contentProvider.isReadOnly()>
throw new UnsupportedOperationException("This content provider is readonly");
<#else>
int uriType = sURIMatcher.match(uri);
SQLiteDatabase db = getDatabase();
int rowsDeleted = 0;
String id;
switch (uriType) {
case ${entity.className?upper_case}_DIR:
rowsDeleted = db.delete(TABLENAME, selection, selectionArgs);
break;
case ${entity.className?upper_case}_ID:
id = uri.getLastPathSegment();
if (TextUtils.isEmpty(selection)) {
rowsDeleted = db.delete(TABLENAME, PK + "=" + id, null);
} else {
rowsDeleted = db.delete(TABLENAME, PK + "=" + id + " and "
+ selection, selectionArgs);
}
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return rowsDeleted;
</#if>
}
<#--
##########################################
########## Update ##############
##########################################
-->
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
<#if contentProvider.isReadOnly()>
throw new UnsupportedOperationException("This content provider is readonly");
<#else>
int uriType = sURIMatcher.match(uri);
SQLiteDatabase db = getDatabase();
int rowsUpdated = 0;
String id;
switch (uriType) {
case ${entity.className?upper_case}_DIR:
rowsUpdated = db.update(TABLENAME, values, selection, selectionArgs);
break;
case ${entity.className?upper_case}_ID:
id = uri.getLastPathSegment();
if (TextUtils.isEmpty(selection)) {
rowsUpdated = db.update(TABLENAME, values, PK + "=" + id, null);
} else {
rowsUpdated = db.update(TABLENAME, values, PK + "=" + id
+ " and " + selection, selectionArgs);
}
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return rowsUpdated;
</#if>
}
<#--
##########################################
########## Query ##############
##########################################
-->
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
int uriType = sURIMatcher.match(uri);
switch (uriType) {
case ${entity.className?upper_case}_DIR:
queryBuilder.setTables(TABLENAME);
break;
case ${entity.className?upper_case}_ID:
queryBuilder.setTables(TABLENAME);
queryBuilder.appendWhere(PK + "="
+ uri.getLastPathSegment());
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
SQLiteDatabase db = getDatabase();
Cursor cursor = queryBuilder.query(db, projection, selection,
selectionArgs, null, null, sortOrder);
cursor.setNotificationUri(getContext().getContentResolver(), uri);
return cursor;
}
<#--
##########################################
########## GetType ##############
##########################################
-->
@Override
public final String getType(Uri uri) {
switch (sURIMatcher.match(uri)) {
case ${entity.className?upper_case}_DIR:
return CONTENT_TYPE;
case ${entity.className?upper_case}_ID:
return CONTENT_ITEM_TYPE;
default :
throw new IllegalArgumentException("Unsupported URI: " + uri);
}
}
}
+129
View File
@@ -0,0 +1,129 @@
<#--
Copyright (C) 2011-2015 Markus Junginger, greenrobot (http://greenrobot.de)
This file is part of greenDAO Generator.
greenDAO Generator is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
greenDAO Generator is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with greenDAO Generator. If not, see <http://www.gnu.org/licenses/>.
-->
<#if entity.toOneRelations?has_content>
private String selectDeep;
protected String getSelectDeep() {
if (selectDeep == null) {
StringBuilder builder = new StringBuilder("SELECT ");
SqlUtils.appendColumns(builder, "T", getAllColumns());
builder.append(',');
<#list entity.toOneRelations as toOne>
SqlUtils.appendColumns(builder, "T${toOne_index}", daoSession.get${toOne.targetEntity.classNameDao}().getAllColumns());
<#if toOne_has_next>
builder.append(',');
</#if>
</#list>
builder.append(" FROM ${entity.tableName} T");
<#list entity.toOneRelations as toOne>
builder.append(" LEFT JOIN ${toOne.targetEntity.tableName} T${toOne_index}<#--
--> ON T.\"${toOne.fkProperties[0].columnName}\"=T${toOne_index}.\"${toOne.targetEntity.pkProperty.columnName}\"");
</#list>
builder.append(' ');
selectDeep = builder.toString();
}
return selectDeep;
}
protected ${entity.className} loadCurrentDeep(Cursor cursor, boolean lock) {
${entity.className} entity = loadCurrent(cursor, 0, lock);
int offset = getAllColumns().length;
<#list entity.toOneRelations as toOne>
${toOne.targetEntity.className} ${toOne.name} = loadCurrentOther(daoSession.get${toOne.targetEntity.classNameDao}(), cursor, offset);
<#if toOne.fkProperties[0].notNull> if(${toOne.name} != null) {
</#if> entity.set${toOne.name?cap_first}(${toOne.name});
<#if toOne.fkProperties[0].notNull>
}
</#if>
<#if toOne_has_next>
offset += daoSession.get${toOne.targetEntity.classNameDao}().getAllColumns().length;
</#if>
</#list>
return entity;
}
public ${entity.className} loadDeep(Long key) {
assertSinglePk();
if (key == null) {
return null;
}
StringBuilder builder = new StringBuilder(getSelectDeep());
builder.append("WHERE ");
SqlUtils.appendColumnsEqValue(builder, "T", getPkColumns());
String sql = builder.toString();
String[] keyArray = new String[] { key.toString() };
Cursor cursor = db.rawQuery(sql, keyArray);
try {
boolean available = cursor.moveToFirst();
if (!available) {
return null;
} else if (!cursor.isLast()) {
throw new IllegalStateException("Expected unique result, but count was " + cursor.getCount());
}
return loadCurrentDeep(cursor, true);
} finally {
cursor.close();
}
}
/** Reads all available rows from the given cursor and returns a list of new ImageTO objects. */
public List<${entity.className}> loadAllDeepFromCursor(Cursor cursor) {
int count = cursor.getCount();
List<${entity.className}> list = new ArrayList<${entity.className}>(count);
if (cursor.moveToFirst()) {
if (identityScope != null) {
identityScope.lock();
identityScope.reserveRoom(count);
}
try {
do {
list.add(loadCurrentDeep(cursor, false));
} while (cursor.moveToNext());
} finally {
if (identityScope != null) {
identityScope.unlock();
}
}
}
return list;
}
protected List<${entity.className}> loadDeepAllAndCloseCursor(Cursor cursor) {
try {
return loadAllDeepFromCursor(cursor);
} finally {
cursor.close();
}
}
/** A raw-style query where you can pass any WHERE clause and arguments. */
public List<${entity.className}> queryDeep(String where, String... selectionArg) {
Cursor cursor = db.rawQuery(getSelectDeep() + where, selectionArg);
return loadDeepAllAndCloseCursor(cursor);
}
</#if>
+101
View File
@@ -0,0 +1,101 @@
<#--
Copyright (C) 2011 Markus Junginger, greenrobot (http://greenrobot.de)
This file is part of greenDAO Generator.
greenDAO Generator is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
greenDAO Generator is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with greenDAO Generator. If not, see <http://www.gnu.org/licenses/>.
-->
package ${schema.defaultJavaPackageDao};
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import de.greenrobot.dao.AbstractDaoMaster;
import de.greenrobot.dao.identityscope.IdentityScopeType;
<#list schema.entities as entity>
import ${entity.javaPackageDao}.${entity.classNameDao};
</#list>
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
/**
* Master of DAO (schema version ${schema.version?c}): knows all DAOs.
*/
public class DaoMaster extends AbstractDaoMaster {
public static final int SCHEMA_VERSION = ${schema.version?c};
/** Creates underlying database table using DAOs. */
public static void createAllTables(SQLiteDatabase db, boolean ifNotExists) {
<#list schema.entities as entity>
<#if !entity.skipTableCreation>
${entity.classNameDao}.createTable(db, ifNotExists);
</#if>
</#list>
}
/** Drops underlying database table using DAOs. */
public static void dropAllTables(SQLiteDatabase db, boolean ifExists) {
<#list schema.entities as entity>
<#if !entity.skipTableCreation>
${entity.classNameDao}.dropTable(db, ifExists);
</#if>
</#list>
}
public static abstract class OpenHelper extends SQLiteOpenHelper {
public OpenHelper(Context context, String name, CursorFactory factory) {
super(context, name, factory, SCHEMA_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
Log.i("greenDAO", "Creating tables for schema version " + SCHEMA_VERSION);
createAllTables(db, false);
}
}
/** WARNING: Drops all table on Upgrade! Use only during development. */
public static class DevOpenHelper extends OpenHelper {
public DevOpenHelper(Context context, String name, CursorFactory factory) {
super(context, name, factory);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.i("greenDAO", "Upgrading schema from version " + oldVersion + " to " + newVersion + " by dropping all tables");
dropAllTables(db, true);
onCreate(db);
}
}
public DaoMaster(SQLiteDatabase db) {
super(db, SCHEMA_VERSION);
<#list schema.entities as entity>
registerDaoClass(${entity.classNameDao}.class);
</#list>
}
public DaoSession newSession() {
return new DaoSession(db, IdentityScopeType.Session, daoConfigMap);
}
public DaoSession newSession(IdentityScopeType type) {
return new DaoSession(db, type, daoConfigMap);
}
}
@@ -0,0 +1,87 @@
<#--
Copyright (C) 2011 Markus Junginger, greenrobot (http://greenrobot.de)
This file is part of greenDAO Generator.
greenDAO Generator is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
greenDAO Generator is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with greenDAO Generator. If not, see <http://www.gnu.org/licenses/>.
-->
package ${schema.defaultJavaPackageDao};
import android.database.sqlite.SQLiteDatabase;
import java.util.Map;
import de.greenrobot.dao.AbstractDao;
import de.greenrobot.dao.AbstractDaoSession;
import de.greenrobot.dao.identityscope.IdentityScopeType;
import de.greenrobot.dao.internal.DaoConfig;
<#list schema.entities as entity>
import ${entity.javaPackage}.${entity.className};
</#list>
<#list schema.entities as entity>
import ${entity.javaPackageDao}.${entity.classNameDao};
</#list>
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
/**
* {@inheritDoc}
*
* @see de.greenrobot.dao.AbstractDaoSession
*/
public class DaoSession extends AbstractDaoSession {
<#list schema.entities as entity>
private final DaoConfig ${entity.classNameDao?uncap_first}Config;
</#list>
<#list schema.entities as entity>
private final ${entity.classNameDao} ${entity.classNameDao?uncap_first};
</#list>
public DaoSession(SQLiteDatabase db, IdentityScopeType type, Map<Class<? extends AbstractDao<?, ?>>, DaoConfig>
daoConfigMap) {
super(db);
<#list schema.entities as entity>
${entity.classNameDao?uncap_first}Config = daoConfigMap.get(${entity.classNameDao}.class).clone();
${entity.classNameDao?uncap_first}Config.initIdentityScope(type);
</#list>
<#list schema.entities as entity>
${entity.classNameDao?uncap_first} = new ${entity.classNameDao}<#--
-->(${entity.classNameDao?uncap_first}Config, this);
</#list>
<#list schema.entities as entity>
registerDao(${entity.className}.class, ${entity.classNameDao?uncap_first});
</#list>
}
public void clear() {
<#list schema.entities as entity>
${entity.classNameDao?uncap_first}Config.getIdentityScope().clear();
</#list>
}
<#list schema.entities as entity>
public ${entity.classNameDao} get${entity.classNameDao?cap_first}() {
return ${entity.classNameDao?uncap_first};
}
</#list>
}
@@ -0,0 +1,53 @@
<#--
Copyright (C) 2011 Markus Junginger, greenrobot (http://greenrobot.de)
This file is part of greenDAO Generator.
greenDAO Generator is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
greenDAO Generator is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with greenDAO Generator. If not, see <http://www.gnu.org/licenses/>.
-->
package ${entity.javaPackageTest};
<#assign isStringPK = entity.pkProperty?? && entity.pkProperty.propertyType == "String" />
<#if isStringPK>
import de.greenrobot.dao.test.AbstractDaoTestStringPk;
<#else>
import de.greenrobot.dao.test.AbstractDaoTestLongPk;
</#if>
import ${entity.javaPackage}.${entity.className};
import ${entity.javaPackageDao}.${entity.classNameDao};
public class ${entity.classNameTest} extends <#if
isStringPK>AbstractDaoTestStringPk<${entity.classNameDao}, ${entity.className}><#else>AbstractDaoTestLongPk<${entity.classNameDao}, ${entity.className}></#if> {
public ${entity.classNameTest}() {
super(${entity.classNameDao}.class);
}
@Override
protected ${entity.className} createEntity(<#if isStringPK>String<#else>Long</#if> key) {
${entity.className} entity = new ${entity.className}();
<#if entity.pkProperty??>
entity.set${entity.pkProperty.propertyName?cap_first}(key);
</#if>
<#list entity.properties as property>
<#if property.notNull>
entity.set${property.propertyName?cap_first}();
</#if>
</#list>
return entity;
}
}
+324
View File
@@ -0,0 +1,324 @@
<#--
Copyright (C) 2011-2015 Markus Junginger, greenrobot (http://greenrobot.de)
This file is part of greenDAO Generator.
greenDAO Generator is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
greenDAO Generator is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with greenDAO Generator. If not, see <http://www.gnu.org/licenses/>.
-->
<#assign toBindType = {"Boolean":"Long", "Byte":"Long", "Short":"Long", "Int":"Long", "Long":"Long", "Float":"Double", "Double":"Double", "String":"String", "ByteArray":"Blob", "Date": "Long" } />
<#assign toCursorType = {"Boolean":"Short", "Byte":"Short", "Short":"Short", "Int":"Int", "Long":"Long", "Float":"Float", "Double":"Double", "String":"String", "ByteArray":"Blob", "Date": "Long" } />
package ${entity.javaPackageDao};
import android.os.Build;
<#if entity.toOneRelations?has_content || entity.incomingToManyRelations?has_content>
import java.util.List;
</#if>
<#if entity.toOneRelations?has_content>
import java.util.ArrayList;
</#if>
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import de.greenrobot.dao.AbstractDao;
import de.greenrobot.dao.Property;
<#if entity.toOneRelations?has_content>
import de.greenrobot.dao.internal.SqlUtils;
</#if>
import de.greenrobot.dao.internal.DaoConfig;
<#if entity.incomingToManyRelations?has_content>
import de.greenrobot.dao.query.Query;
import de.greenrobot.dao.query.QueryBuilder;
</#if>
<#if entity.javaPackageDao != schema.defaultJavaPackageDao>
import ${schema.defaultJavaPackageDao}.DaoSession;
</#if>
<#if entity.additionalImportsDao?has_content>
<#list entity.additionalImportsDao as additionalImport>
import ${additionalImport};
</#list>
</#if>
import ${entity.javaPackage}.${entity.className};
<#if entity.protobuf>
import ${entity.javaPackage}.${entity.className}.Builder;
</#if>
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
/**
* DAO for table "${entity.tableName}".
*/
public class ${entity.classNameDao} extends AbstractDao<${entity.className}, ${entity.pkType}> {
public static final String TABLENAME = "${entity.tableName}";
/**
* Properties of entity ${entity.className}.<br/>
* Can be used for QueryBuilder and for referencing column names.
*/
public static class Properties {
<#list entity.propertiesColumns as property>
public final static Property ${property.propertyName?cap_first} = new Property(${property_index}, ${property.javaType}.class, "${property.propertyName}", ${property.primaryKey?string}, "${property.columnName}");
</#list>
};
<#if entity.active>
private DaoSession daoSession;
</#if>
<#list entity.properties as property><#if property.customType?has_content><#--
--> private final ${property.converterClassName} ${property.propertyName}Converter = new ${property.converterClassName}();
</#if></#list>
<#list entity.incomingToManyRelations as toMany>
private Query<${toMany.targetEntity.className}> ${toMany.sourceEntity.className?uncap_first}_${toMany.name?cap_first}Query;
</#list>
public ${entity.classNameDao}(DaoConfig config) {
super(config);
}
public ${entity.classNameDao}(DaoConfig config, DaoSession daoSession) {
super(config, daoSession);
<#if entity.active>
this.daoSession = daoSession;
</#if>
}
<#if !entity.skipTableCreation>
/** Creates the underlying database table. */
public static void createTable(SQLiteDatabase db, boolean ifNotExists) {
String constraint = ifNotExists? "IF NOT EXISTS ": "";
db.execSQL("CREATE TABLE " + constraint + "\"${entity.tableName}\" (" + //
<#assign pks = []>
<#list entity.propertiesColumns as property>
<#if property.constraints??><#if property.constraints?contains("PRIMARY KEY")><#assign pks = pks + [property.columnName]></#if></#if>
</#list>
<#if pks?size gt 1>
<#list entity.propertiesColumns as property>
"\"${property.columnName}\" ${property.columnType}<#if property.constraints??> ${property.constraints?replace("PRIMARY KEY","")} </#if>," + // ${property_index}: ${property.propertyName}
</#list>
"PRIMARY KEY (" +
<#list pks as pk>
"\"${pk}\" <#if pk_has_next>," +<#else>) ON CONFLICT REPLACE)" + ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) ? " WITHOUT ROWID;" : ";")</#if>
</#list>
);
<#else>
<#list entity.propertiesColumns as property>
"\"${property.columnName}\" ${property.columnType}<#if property.constraints??> ${property.constraints} </#if><#if property_has_next>," +<#else>);");</#if> // ${property_index}: ${property.propertyName}
</#list>
</#if>
<#if entity.indexes?has_content >
// Add Indexes
<#list entity.indexes as index>
db.execSQL("CREATE <#if index.unique>UNIQUE </#if>INDEX " + constraint + "${index.name} ON ${entity.tableName}" +
" (<#list index.properties
as property>\"${property.columnName}\"<#if property_has_next>,</#if></#list>);");
</#list>
</#if>
}
/** Drops the underlying database table. */
public static void dropTable(SQLiteDatabase db, boolean ifExists) {
String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "\"${entity.tableName}\"";
db.execSQL(sql);
}
</#if>
/** @inheritdoc */
@Override
protected void bindValues(SQLiteStatement stmt, ${entity.className} entity) {
stmt.clearBindings();
<#list entity.properties as property>
<#if property.notNull || entity.protobuf>
<#if entity.protobuf>
if(entity.has${property.propertyName?cap_first}()) {
</#if> stmt.bind${toBindType[property.propertyType]}(${property_index + 1}, ${property.databaseValueExpressionNotNull});
<#if entity.protobuf>
}
</#if>
<#else> <#-- nullable, non-protobuff -->
${property.javaTypeInEntity} ${property.propertyName} = entity.get${property.propertyName?cap_first}();
if (${property.propertyName} != null) {
stmt.bind${toBindType[property.propertyType]}(${property_index + 1}, ${property.databaseValueExpression});
}
</#if>
</#list>
<#list entity.toOneRelations as toOne>
<#if !toOne.fkProperties?has_content>
${toOne.targetEntity.className} ${toOne.name} = entity.peak${toOne.name?cap_first}();
if(${toOne.name} != null) {
${toOne.targetEntity.pkProperty.javaType} ${toOne.name}__targetKey = ${toOne.name}.get${toOne.targetEntity.pkProperty.propertyName?cap_first}();
<#if !toOne.targetEntity.pkProperty.notNull>
if(${toOne.name}__targetKey != null) {
// TODO bind ${toOne.name}__targetKey
}
<#else>
// TODO bind ${toOne.name}__targetKey
</#if>
}
</#if>
</#list>
}
<#if entity.active>
@Override
protected void attachEntity(${entity.className} entity) {
super.attachEntity(entity);
entity.__setDaoSession(daoSession);
}
</#if>
/** @inheritdoc */
@Override
public ${entity.pkType} readKey(Cursor cursor, int offset) {
<#if entity.pkProperty??>
return <#if !entity.pkProperty.notNull>cursor.isNull(offset + ${entity.pkProperty.ordinal}) ? null : </#if><#if
entity.pkProperty.propertyType == "Byte">(byte) </#if><#if
entity.pkProperty.propertyType == "Date">new java.util.Date(</#if>cursor.get${toCursorType[entity.pkProperty.propertyType]}(offset + ${entity.pkProperty.ordinal})<#if
entity.pkProperty.propertyType == "Boolean"> != 0</#if><#if
entity.pkProperty.propertyType == "Date">)</#if>;
<#else>
return null;
</#if>
}
/** @inheritdoc */
@Override
public ${entity.className} readEntity(Cursor cursor, int offset) {
<#if entity.protobuf>
Builder builder = ${entity.className}.newBuilder();
<#list entity.properties as property>
<#if !property.notNull>
if (!cursor.isNull(offset + ${property_index})) {
</#if> builder.set${property.propertyName?cap_first}(cursor.get${toCursorType[property.propertyType]}(offset + ${property_index}));
<#if !property.notNull>
}
</#if>
</#list>
return builder.build();
<#elseif entity.constructors>
<#--
############################## readEntity non-protobuff, constructor ##############################
-->
${entity.className} entity = new ${entity.className}( //
<#list entity.properties as property>
<#if !property.notNull>cursor.isNull(offset + ${property_index}) ? null : </#if><#--
-->${property.getEntityValueExpression("cursor.get${toCursorType[property.propertyType]}(offset + ${property_index})")}<#--
--><#if property_has_next>,</#if> // ${property.propertyName}
</#list>
);
return entity;
<#else>
<#--
############################## readEntity non-protobuff, setters ##############################
-->
${entity.className} entity = new ${entity.className}();
readEntity(cursor, entity, offset);
return entity;
</#if>
}
/** @inheritdoc */
@Override
public void readEntity(Cursor cursor, ${entity.className} entity, int offset) {
<#if entity.protobuf>
throw new UnsupportedOperationException("Protobuf objects cannot be modified");
<#else>
<#list entity.properties as property>
entity.set${property.propertyName?cap_first}(<#if !property.notNull>cursor.isNull(offset + ${property_index}) ? null : </#if><#--
-->${property.getEntityValueExpression("cursor.get${toCursorType[property.propertyType]}(offset + ${property_index})")});
</#list>
</#if>
}
/** @inheritdoc */
@Override
protected ${entity.pkType} updateKeyAfterInsert(${entity.className} entity, long rowId) {
<#if entity.pkProperty??>
<#if entity.pkProperty.propertyType == "Long">
<#if !entity.protobuf>
entity.set${entity.pkProperty.propertyName?cap_first}(rowId);
</#if>
return rowId;
<#else>
return entity.get${entity.pkProperty.propertyName?cap_first}();
</#if>
<#else>
// Unsupported or missing PK type
return null;
</#if>
}
/** @inheritdoc */
@Override
public ${entity.pkType} getKey(${entity.className} entity) {
<#if entity.pkProperty??>
if(entity != null) {
return entity.get${entity.pkProperty.propertyName?cap_first}();
} else {
return null;
}
<#else>
return null;
</#if>
}
/** @inheritdoc */
@Override
protected boolean isEntityUpdateable() {
return ${(!entity.protobuf)?string};
}
<#list entity.incomingToManyRelations as toMany>
/** Internal query to resolve the "${toMany.name}" to-many relationship of ${toMany.sourceEntity.className}. */
public List<${toMany.targetEntity.className}> _query${toMany.sourceEntity.className?cap_first}_${toMany.name?cap_first}(<#--
--><#if toMany.targetProperties??><#list toMany.targetProperties as property><#--
-->${property.javaType} ${property.propertyName}<#if property_has_next>, </#if></#list><#else><#--
-->${toMany.sourceProperty.javaType} ${toMany.sourceProperty.propertyName}</#if>) {
synchronized (this) {
if (${toMany.sourceEntity.className?uncap_first}_${toMany.name?cap_first}Query == null) {
QueryBuilder<${toMany.targetEntity.className}> queryBuilder = queryBuilder();
<#if toMany.targetProperties??>
<#list toMany.targetProperties as property>
queryBuilder.where(Properties.${property.propertyName?cap_first}.eq(null));
</#list>
<#else>
queryBuilder.join(${toMany.joinEntity.className}.class, ${toMany.joinEntity.classNameDao}.Properties.${toMany.targetProperty.propertyName?cap_first})
.where(${toMany.joinEntity.classNameDao}.Properties.${toMany.sourceProperty.propertyName?cap_first}.eq(${toMany.sourceProperty.propertyName}));
</#if>
<#if toMany.order?has_content>
queryBuilder.orderRaw("${toMany.order}");
</#if>
${toMany.sourceEntity.className?uncap_first}_${toMany.name?cap_first}Query = queryBuilder.build();
}
}
Query<${toMany.targetEntity.className}> query = ${toMany.sourceEntity.className?uncap_first}_${toMany.name?cap_first}Query.forCurrentThread();
<#if toMany.targetProperties??>
<#list toMany.targetProperties as property>
query.setParameter(${property_index}, ${property.propertyName});
</#list>
<#else>
query.setParameter(0, ${toMany.sourceProperty.propertyName});
</#if>
return query.list();
}
</#list>
<#if entity.toOneRelations?has_content>
<#include "dao-deep.ftl">
</#if>
}
+287
View File
@@ -0,0 +1,287 @@
<#--
Copyright (C) 2011-2015 Markus Junginger, greenrobot (http://greenrobot.de)
This file is part of greenDAO Generator.
greenDAO Generator is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
greenDAO Generator is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with greenDAO Generator. If not, see <http://www.gnu.org/licenses/>.
-->
<#assign toBindType = {"Boolean":"Long", "Byte":"Long", "Short":"Long", "Int":"Long", "Long":"Long", "Float":"Double", "Double":"Double", "String":"String", "ByteArray":"Blob" }/>
<#assign toCursorType = {"Boolean":"Short", "Byte":"Short", "Short":"Short", "Int":"Int", "Long":"Long", "Float":"Float", "Double":"Double", "String":"String", "ByteArray":"Blob" }/>
<#assign complexTypes = ["String", "ByteArray", "Date"]/>
package ${entity.javaPackage};
<#if entity.toManyRelations?has_content>
import java.util.List;
</#if>
<#if entity.active>
import ${schema.defaultJavaPackageDao}.DaoSession;
import de.greenrobot.dao.DaoException;
</#if>
<#if entity.additionalImportsEntity?has_content>
<#list entity.additionalImportsEntity as additionalImport>
import ${additionalImport};
</#list>
</#if>
<#if entity.hasKeepSections>
// THIS CODE IS GENERATED BY greenDAO, EDIT ONLY INSIDE THE "KEEP"-SECTIONS
// KEEP INCLUDES - put your custom includes here
<#if keepIncludes?has_content>${keepIncludes!}</#if>// KEEP INCLUDES END
<#else>
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT. Enable "keep" sections if you want to edit.
</#if>
<#if entity.javaDoc ??>
${entity.javaDoc}
<#else>
/**
* Entity mapped to table "${entity.tableName}".
*/
</#if>
<#if entity.codeBeforeClass ??>
${entity.codeBeforeClass}
</#if>
public class ${entity.className}<#if
entity.superclass?has_content> extends ${entity.superclass} </#if><#if
entity.interfacesToImplement?has_content> implements <#list entity.interfacesToImplement
as ifc>${ifc}<#if ifc_has_next>, </#if></#list></#if> {
<#list entity.properties as property>
<#if property.notNull && complexTypes?seq_contains(property.propertyType)>
/** Not-null value. */
</#if>
<#if property.javaDocField ??>
${property.javaDocField}
</#if>
<#if property.codeBeforeField ??>
${property.codeBeforeField}
</#if>
private ${property.javaTypeInEntity} ${property.propertyName};
</#list>
<#if entity.active>
/** Used to resolve relations */
private transient DaoSession daoSession;
/** Used for active entity operations. */
private transient ${entity.classNameDao} myDao;
<#list entity.toOneRelations as toOne>
private ${toOne.targetEntity.className} ${toOne.name};
<#if toOne.useFkProperty>
private ${toOne.resolvedKeyJavaType[0]} ${toOne.name}__resolvedKey;
<#else>
private boolean ${toOne.name}__refreshed;
</#if>
</#list>
<#list entity.toManyRelations as toMany>
private List<${toMany.targetEntity.className}> ${toMany.name};
</#list>
</#if>
<#if entity.hasKeepSections>
// KEEP FIELDS - put your custom fields here
${keepFields!} // KEEP FIELDS END
</#if>
<#if entity.constructors>
public ${entity.className}() {
}
<#if entity.propertiesPk?has_content && entity.propertiesPk?size != entity.properties?size>
public ${entity.className}(<#list entity.propertiesPk as
property>${property.javaType} ${property.propertyName}<#if property_has_next>, </#if></#list>) {
<#list entity.propertiesPk as property>
this.${property.propertyName} = ${property.propertyName};
</#list>
}
</#if>
public ${entity.className}(<#list entity.properties as
property>${property.javaTypeInEntity} ${property.propertyName}<#if property_has_next>, </#if></#list>) {
<#list entity.properties as property>
this.${property.propertyName} = ${property.propertyName};
</#list>
}
</#if>
<#if entity.active>
/** called by internal mechanisms, do not call yourself. */
public void __setDaoSession(DaoSession daoSession) {
this.daoSession = daoSession;
myDao = daoSession != null ? daoSession.get${entity.classNameDao?cap_first}() : null;
}
</#if>
<#list entity.properties as property>
<#if property.notNull && complexTypes?seq_contains(property.propertyType)>
/** Not-null value. */
</#if>
<#if property.javaDocGetter ??>
${property.javaDocGetter}
</#if>
<#if property.codeBeforeGetter ??>
${property.codeBeforeGetter}
</#if>
public ${property.javaTypeInEntity} get${property.propertyName?cap_first}() {
return ${property.propertyName};
}
<#if property.notNull && complexTypes?seq_contains(property.propertyType)>
/** Not-null value; ensure this value is available before it is saved to the database. */
</#if>
<#if property.javaDocSetter ??>
${property.javaDocSetter}
</#if>
<#if property.codeBeforeSetter ??>
${property.codeBeforeSetter}
</#if>
public void set${property.propertyName?cap_first}(${property.javaTypeInEntity} ${property.propertyName}) {
this.${property.propertyName} = ${property.propertyName};
}
</#list>
<#--
##########################################
########## To-One Relations ##############
##########################################
-->
<#list entity.toOneRelations as toOne>
/** To-one relationship, resolved on first access. */
public ${toOne.targetEntity.className} get${toOne.name?cap_first}() {
<#if toOne.useFkProperty>
${toOne.fkProperties[0].javaType} __key = this.${toOne.fkProperties[0].propertyName};
if (${toOne.name}__resolvedKey == null || <#--
--><#if toOne.resolvedKeyUseEquals[0]>!${toOne.name}__resolvedKey.equals(__key)<#--
--><#else>!${toOne.name}__resolvedKey.equals(__key)</#if>) {
if (daoSession == null) {
throw new DaoException("Entity is detached from DAO context");
}
${toOne.targetEntity.classNameDao} targetDao = daoSession.get${toOne.targetEntity.classNameDao?cap_first}();
${toOne.targetEntity.className} ${toOne.name}New = targetDao.load(__key);
synchronized (this) {
${toOne.name} = ${toOne.name}New;
${toOne.name}__resolvedKey = __key;
}
}
<#else>
if (${toOne.name} != null || !${toOne.name}__refreshed) {
if (daoSession == null) {
throw new DaoException("Entity is detached from DAO context");
}
${toOne.targetEntity.classNameDao} targetDao = daoSession.get${toOne.targetEntity.classNameDao?cap_first}();
targetDao.refresh(${toOne.name});
${toOne.name}__refreshed = true;
}
</#if>
return ${toOne.name};
}
<#if !toOne.useFkProperty>
/** To-one relationship, returned entity is not refreshed and may carry only the PK property. */
public ${toOne.targetEntity.className} peak${toOne.name?cap_first}() {
return ${toOne.name};
}
</#if>
public void set${toOne.name?cap_first}(${toOne.targetEntity.className} ${toOne.name}) {
<#if toOne.fkProperties[0].notNull>
if (${toOne.name} == null) {
throw new DaoException("To-one property '${toOne.fkProperties[0].propertyName}' has not-null constraint; cannot set to-one to null");
}
</#if>
synchronized (this) {
this.${toOne.name} = ${toOne.name};
<#if toOne.useFkProperty>
${toOne.fkProperties[0].propertyName} = <#if !toOne.fkProperties[0].notNull>${toOne.name} == null ? null : </#if>${toOne.name}.get${toOne.targetEntity.pkProperty.propertyName?cap_first}();
${toOne.name}__resolvedKey = ${toOne.fkProperties[0].propertyName};
<#else>
${toOne.name}__refreshed = true;
</#if>
}
}
</#list>
<#--
##########################################
########## To-Many Relations #############
##########################################
-->
<#list entity.toManyRelations as toMany>
/** To-many relationship, resolved on first access (and after reset). Changes to to-many relations are not persisted, make changes to the target entity. */
public List<${toMany.targetEntity.className}> get${toMany.name?cap_first}() {
if (${toMany.name} == null) {
if (daoSession == null) {
throw new DaoException("Entity is detached from DAO context");
}
${toMany.targetEntity.classNameDao} targetDao = daoSession.get${toMany.targetEntity.classNameDao?cap_first}();
List<${toMany.targetEntity.className}> ${toMany.name}New = targetDao._query${toMany.sourceEntity.className?cap_first}_${toMany.name?cap_first}(<#--
--><#if toMany.sourceProperties??><#list toMany.sourceProperties as property>${property.propertyName}<#if property_has_next>, </#if></#list><#else><#--
-->${entity.pkProperty.propertyName}</#if>);
synchronized (this) {<#-- Check if another thread was faster, we cannot lock while doing the query to prevent deadlocks -->
if(${toMany.name} == null) {
${toMany.name} = ${toMany.name}New;
}
}
}
return ${toMany.name};
}
/** Resets a to-many relationship, making the next get call to query for a fresh result. */
public synchronized void reset${toMany.name?cap_first}() {
${toMany.name} = null;
}
</#list>
<#--
##########################################
########## Active entity operations ######
##########################################
-->
<#if entity.active>
/** Convenient call for {@link AbstractDao#delete(Object)}. Entity must attached to an entity context. */
public void delete() {
if (myDao == null) {
throw new DaoException("Entity is detached from DAO context");
}
myDao.delete(this);
}
/** Convenient call for {@link AbstractDao#update(Object)}. Entity must attached to an entity context. */
public void update() {
if (myDao == null) {
throw new DaoException("Entity is detached from DAO context");
}
myDao.update(this);
}
/** Convenient call for {@link AbstractDao#refresh(Object)}. Entity must attached to an entity context. */
public void refresh() {
if (myDao == null) {
throw new DaoException("Entity is detached from DAO context");
}
myDao.refresh(this);
}
</#if>
<#if entity.hasKeepSections>
// KEEP METHODS - put your custom methods here
${keepMethods!} // KEEP METHODS END
</#if>
}