greenDAO
greenDAO copied to clipboard
Custom primary key type generate wrong code
== Summary == When primary key is a custom type, the generated code for updateKeyAfterInsert and getKey will use String as return type instead of the actual custom type, which will cause compile error.
-- code to reproduce --
@Entity
public class Example {
@Convert(converter = UUIDConverter.class, columnType = String.class)
@Id
private UUID id;
static class UUIDConverter implements PropertyConverter<UUID, String> {
@Override
public UUID convertToEntityProperty(String databaseValue) {
return UUID.fromString(databaseValue);
}
@Override
public String convertToDatabaseValue(UUID entityProperty) {
return entityProperty.toString();
}
}
}
the generated ExampleDao would be
public class ExampleDao extends AbstractDao<Example, String> {
... ...
@Override
protected final String updateKeyAfterInsert(Example entity, long rowId) {
return entity.getId(); // this won't compile because entity.getId() returns UUID
}
@Override
public String getKey(Example entity) {
if(entity != null) {
return entity.getId(); // this won't compile because entity.getId() returns UUID
} else {
return null;
}
}
... ...
}
The problem is the custom type was not considered when set up the value for pkType
of Entity, which is processed in Entity.java
void init2ndPass() {
... ...
if (propertiesPk.size() == 1) {
pkProperty = propertiesPk.get(0);
pkType = schema.mapToJavaTypeNullable(pkProperty.getPropertyType());
} else {
pkType = "Void";
}
... ...
}
Also, if Entity was generated programmatically, for example
Entity entity = schema.addEntity("CustomPkTypeEntity");
entity.addStringProperty("id").customType("java.util.UUID", "org.greenrobot.greendao.daotest.customtype.UuidConverter").primaryKey();
entity.addIntProperty("value");
then the generated Entity code would be
private UUID id;
public CustomPkTypeEntity(String id) { // this won't compile
this.id = id;
}
which String id
should be UUID id
.
Please see PR https://github.com/greenrobot/greenDAO/pull/1053 for fix details